默认参数的问题
Stanley B. Lippman*、* Josée Lajoie 所著的《C++ Primer》一书中的
《类构造函数》第 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:
// ...
};
以下都是合法的 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() ))
// ...
}
这本书似乎非常不清楚,代码不完整。 需要对构造函数有一个很好的解释。请澄清。
In the Book C++ Primer by Stanley B. Lippman*,* Josée Lajoie
in Chapter 14.2 of Class Constructors it states:
Should we also provide support for specifying an opening balance but no client name?
As it happens, the class specification disallows this explicitly. Our two-parameter
constructor with a default second argument provides a complete interface for accepting
initial values for the data members of class Account that can be set by the user:
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:
// ...
};
The following are both legal Account class object definitions passing one or two arguments to our constructor:
int main()
{
// ok: both invoke two-parameter constructor
Account acct( "Ethan Stern" );
How does this Invoke the 2-parameter constructor when it has not been declared with single argument??
Account *pact = new Account( "Michael Lieberman", 5000 );
And how does the above line call the constructor with default arguments
if ( strcmp( acct.name(), pact->name() ))
// ...
}
The book seems to be highly unclear with incomplete codes.
Need a good explanation on Constructors. Please clarify.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这与构造函数无关,而是与默认参数有关。
当您调用它提供较少的参数时,它使用默认参数的值。
例如,
如果函数参数之一具有默认值,则所有后续参数也必须具有默认值。
华泰
This isn't about constuctors, this is about default arguments.
when you call it providing less arguments, it uses the values of default arguments.
E.g.
If one of the function parameters has a default value, then all successive parameters must have ones too.
HTH