带默认参数的复制构造函数
据我所知,复制构造函数必须采用 T(const T&)
或 T(T&)
形式。如果我想向签名添加默认参数怎么办?
T(const T&, double f = 1.0);
这符合标准吗?
As far as I know, the copy constructor must be of the form T(const T&)
or T(T&)
. What if I wanted to add default arguments to the signature?
T(const T&, double f = 1.0);
Would that be standards compliant?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的。
§[class.copy]/2:
Yes.
§[class.copy]/2:
您可以只创建两个不同的构造函数:
但是,您所拥有的可以作为复制构造函数。
顺便说一句,我发现在 C++ 中使用默认参数通常不是一个好主意,而使用重载会更好,其中参数较少的参数使用默认值调用参数较多的参数(当然,这对于 ISO C++ 2003 中的构造函数是不可能的,但在 ISO C++ 201x 中允许委托构造函数。这样做的原因是默认值给你的函数提供了与其表面行为不同的实际签名,这使得在获取指向函数的指针时变得有些困难/痛苦。通过提供重载,可以获取每种可能的调用类型的函数指针,而不需要任何类型的“绑定”机制来使其工作。
You can just create two different constructors:
However, what you have is permitted as a copy constructor.
On a side note, I have discovered that it is generally not a good idea to use default parameters in C++, and it is instead much better to use overloads, where the ones with fewer parameters invoke the ones with more parameters, using default values (of course that isn't possible with constructors in ISO C++ 2003, but delegating constructors are permitted in ISO C++ 201x). The reason for this is that default values give your functions different actual signatures than their apparent behavior, making it somewhat difficult/painful when taking the pointers to the functions. By providing overloads, function pointers of each possible invocation type can be taken without requiring any sort of "binding" mechanism to make it work.