Sad*_*que 1 c++ default-arguments
在Stanley B. Lippman*的书C++入门书中,*JoséeLajoie
在类构造函数的第14.2章中,它指出:
我们是否还应该为指定期初余额但没有客户名称提供支持?碰巧,类规范明确禁止这样做.我们的带有默认第二个参数的双参数构造函数提供了一个完整的接口,用于接受可由用户设置的类Account的数据成员的初始值:
class Account {
public:
// default constructor ...
Account();
// parameter names are not necessary in declaration
Account( const char*, double=0.0 );
const char* name() { return _name; } // What is this for??
// ...
private:
// ...
};
Run Code Online (Sandbox Code Playgroud)
以下是合法的Account类对象定义,将一个或两个参数传递给构造函数:
int main()
{
// ok: both invoke two-parameter constructor
Account acct( "Ethan Stern" );
Run Code Online (Sandbox Code Playgroud)
当没有使用单个参数声明时,如何调用2参数构造函数?
Account *pact = new Account( "Michael Lieberman", 5000 );
Run Code Online (Sandbox Code Playgroud)
以上行如何使用默认参数调用构造函数
if ( strcmp( acct.name(), pact->name() ))
// ...
}
Run Code Online (Sandbox Code Playgroud)
对于不完整的代码,这本书似乎非常不清楚.需要对构造函数进行很好的解释.请澄清.
这不是关于constuctors,这是关于默认参数.
void f(int x, int y = 5)
{
//blah
}
Run Code Online (Sandbox Code Playgroud)
当你调用它提供较少的参数时,它使用默认参数的值.例如
f(3); //equivalent to f(3, 5);
Run Code Online (Sandbox Code Playgroud)
如果其中一个函数参数具有默认值,则所有连续参数也必须具有默认值.
void f(int x, int y = 3, int z = 4)
{
//blah
}
f(0); // f(0, 3, 4)
f(1, 2); //f(1, 2, 4)
f(10, 30, 20); //explicitly specifying arguments
Run Code Online (Sandbox Code Playgroud)
HTH