多个默认构造函数 [英] Multiple Default Constructors

查看:357
本文介绍了多个默认构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自此堆栈溢出问题答案包含以下内容引用:

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?

推荐答案

默认构造函数不必具有任何参数.他们只需要无言以对即可.

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]: X类的默认构造函数是X类的构造函数,对于该构造函数,每个不是函数参数包的参数都具有默认参数(包括没有参数的构造函数的情况). [..]

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

现在,当然,在此示例中,您实际上不能在不提供参数的情况下使用它们中的任何一个来实例化Foo(调用将是模棱两可的).但是Foo仍然可用,并且它们仍然是默认构造函数".该标准就是为了定义规则而决定对事物进行分类的方式.它并不会真正影响您的代码或编程.

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.

(顺便说一句,我不想​​分散注意力,但您都应该在这两个位置上都使用explicit!)

这篇关于多个默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆