Why I get the error: "there is more than one default constructor"?
Why I get the error: "there is more than one default constructor"?
我收到消息:
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 构造函数,还是调用默认值为 1
.
的 int
构造函数
消除这种歧义的一种方法是删除 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;
}
我收到消息:
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 构造函数,还是调用默认值为 1
.
int
构造函数
消除这种歧义的一种方法是删除 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;
}