gpt4 book ai didi

c++ - 为什么我收到错误: “there is more than one default constructor” ?

转载 作者:行者123 更新时间:2023-12-02 11:12:25 26 4
gpt4 key购买 nike

我收到消息:

Severity Code Description Project File Line Suppression State Error (active) E0339 class "D" has more than one default constructor)



和:

Severity Code Description Project File Line Suppression State Error C2668 'D::D': ambiguous call to overloaded function)



错误发生在标记为//(2)的行中

如果删除标记///(1)的行,则可以构建代码。
class C {
int i, j;

public:
C(int x, int y) : i(x), j(y)
{
cout << "Konstr C" << endl;
}
C() : i(0), j(0)
{
cout << "Std-Konstr C" << endl;
}
~C()
{
cout << "Destruktor C" << endl;
}
};
class D : public C {
int k, a, b;
C c;
public:

D():c(){ cout << "Std-Konstr D" << endl; }// (1)

D(int x = 1) :c(x, 1), a(x), b(0), k(19)

{
cout << "Konstr-1 D" << endl;
}
D(int x, int y, int z) :C(x, y), a(1), b(2), c(x, y), k(z)
{
cout << "Konstr-2 D" << endl;
}
~D()
{
cout << "Destruktor D" << endl;
}
};
class E : public D {
int m;
C c;
D b;
public:
E(int x, int y) : c(2, 3), b(y), m(x + y)// (2)
{
cout << "Konstr E" << endl;
}
~E()
{
cout << "Destruktor E" << endl;
}
};

最佳答案

如错误消息所述,D()是不明确的。编译器无法知道是要调用no-arg构造函数,还是要使用默认值int调用1构造函数。

消除这种歧义的一种方法是删除x参数的默认值:

D():c(){ cout << "Std-Konstr D" << endl; }// (1)

D(int x) :c(x, 1), a(x), b(0), k(19)
// ^-- x=1 was removed here
{
cout << "Konstr-1 D" << endl;
}

关于c++ - 为什么我收到错误: “there is more than one default constructor” ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56093952/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com