copy constructor with default arguments

偶尔善良 提交于 2019-12-03 19:51:02

问题


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?


回答1:


Yes.

§[class.copy]/2:

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments [ Example: X::X(const X&) and X::X(X&,int=1) are copy constructors.




回答2:


You can just create two different constructors:

T(const T&)
T(const T&,double)

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.



来源:https://stackoverflow.com/questions/2787569/copy-constructor-with-default-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!