为什么会收到错误消息:“有多个默认构造函数”?

时间:2019-05-11 20:16:49

标签: c++ constructor compiler-errors c++17 default-constructor

我收到消息:

  

严重性代码描述项目文件行抑制状态   错误(活动)E0339类“ D”具有多个默认构造函数)

和:

  

严重性代码说明项目文件行抑制状态错误C2668'D :: D':对重载函数的歧义调用

该错误发生在标记为//(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;
    }
};

1 个答案:

答案 0 :(得分:1)

错误消息指出,D()含糊不清。编译器无法知道是要调用no-arg构造函数,还是要调用默认值int的{​​{1}}构造函数。

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

x
相关问题