简体   繁体   English

默认构造函数和默认参数构造函数如何导致 cpp 中的歧义?

[英]How can a default constructor and a default argument constructor cause ambiguity in cpp?

Whats the difference between the default constructor and deafult argument constructor?默认构造函数和默认参数构造函数之间有什么区别? An example will be helpful一个例子会有所帮助

I suppose you mean something like this:我想你的意思是这样的:

struct foo {
    foo(int x = 1) {}
    foo() {}
};

A default constructor is one that can be called without arguments (and I suppose that is what you misunderstood). 默认构造函数是可以不带参数调用的 构造函数(我想这就是您误解的地方)。 Both constructors above are default constructors.上面的两个构造函数都是默认构造函数。 They both can be called without arguments and when you call the constructor via它们都可以在没有参数的情况下调用,当您通过调用构造函数时

foo f;

Both are viable and there is no way for the compiler to resolve the ambiguity.两者都是可行的,编译器无法解决歧义。

A constructor where all the arguments have defaults is also a default constructor for the class.构造函数,所有的参数都默认也是该类的默认构造函数。

struct Foo
{
    Foo() = default;
    Foo(int = 0){};
};

int main() {
    Foo f;
}

will not compile as there are two candidate default constructors so overload resolution will fail.不会编译,因为有两个候选默认构造函数,因此重载解析将失败。 (Note that Foo f(1); will compile as overload resolution is no longer ambiguous.) (请注意, Foo f(1);将编译为重载决议不再模棱两可。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM