在 Stanley B. Lippman 的 C++ Primer 一书中*,* Josée Lajoie
在 Class Constructors 的第 14.2 章中,它指出:
我们是否还应该支持指定期初余额但不指定客户名称? 碰巧的是,类规范明确不允许这样做。我们的双参数 带有默认第二个参数的构造函数提供了一个完整的接口(interface)来接受 可由用户设置的 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:
// ...
};
以下都是合法的 Account 类对象定义,将一个或两个参数传递给我们的构造函数:
int main()
{
// ok: both invoke two-parameter constructor
Account acct( "Ethan Stern" );
当没有用单个参数声明时,如何调用 2 参数构造函数??
Account *pact = new Account( "Michael Lieberman", 5000 );
以及上面那行是如何使用默认参数调用构造函数的
if ( strcmp( acct.name(), pact->name() ))
// ...
}
这本书似乎很不清楚,代码不完整。 需要对构造函数进行很好的解释。请澄清。
最佳答案
这不是关于构造函数,这是关于默认参数。
void f(int x, int y = 5)
{
//blah
}
当您调用它时提供较少的参数,它会使用默认参数的值。 例如
f(3); //equivalent to f(3, 5);
如果其中一个函数参数具有默认值,则所有后续参数也必须具有默认值。
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
HTH
关于c++ - 默认参数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5448930/