Multiple Default Constructors

╄→гoц情女王★ 提交于 2020-04-11 08:38:11

问题


From this stack overflow question the answer contains this quote:

... definition says that all default constructors (in case there are multiple) ...

How can there be multiple default constructors, and why may that be useful or allowed by the standard?


回答1:


Default constructors don't have to have no parameters; they just need to be invocable with no arguments.

This condition is fulfilled by any constructor whose arguments all have defaults.

[class.dtor/1]: A default constructor for a class X is a constructor of class X for which each parameter that is not a function parameter pack has a default argument (including the case of a constructor with no parameters). [..]

struct Foo
{
   Foo(int a = 0);
   Foo(std::string str = "");
};

Now, of course, in this example you cannot actually instantiate a Foo using either of them without providing an argument (the call would be ambiguous). But Foo is still usable, and these are still "default constructors". That's just how the standard has decided to categorise things, for the purpose of defining rules. It doesn't really affect your code or programming.

(By the way, I didn't want to distract but you should have explicit on both of those!)



来源:https://stackoverflow.com/questions/60877011/multiple-default-constructors

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