【问题标题】:C++ / MFC multiple inheritance calling base class constructorC++/MFC多重继承调用基类构造函数
【发布时间】:2013-02-08 11:56:18
【问题描述】:

我在 派生 类的两个构造函数定义中都收到 error C2512: 'derived' : no proper default constructor available 错误。我的代码如下所示。我该如何解决这个问题?

Class A
{
    int a, int b;
    A(int x, int y)
    {
        sme code....
    }
}

Class B
{
    int a, int b, int c;
    B(int x, int y, int Z)
    {
        sme code....
    }
}


Class derived : public A, public B
{
    derived(int a, int b):A(a, b)
    {

    }

    derived(int a, int b, int c):B(a, b, c)
    {

    }
}

【问题讨论】:

标签: c++ visual-c++ mfc


【解决方案1】:

其中一个问题是,在每个派生类的构造函数中,您只将适当的构造函数参数转发给两个基类中的一个。它们都没有默认构造函数,因此您需要为基类AB 的构造显式提供参数。

第二个问题是你的基类的构造函数被隐式声明为private,所以基类不能访问它们。您应该将它们设为public 或至少protected

小问题:在类定义之后,你需要放一个分号。另外,声明类的关键字是class,而不是Class

class A // <---- Use the "class" keyword
{
public: // <---- Make the constructor accessible to derived classes
     int a, int b; 
     A(int x, int y) 
     { 
         some code.... 
     } 
}; // <---- Don't forget the semicolon

class B // <---- Use the "class" keyword
{
public: // <---- Make the constructor accessible to derived classes
    int a, int b, int c;
    B(int x, int y, int Z)
    {
        sme code....
    }
}; // <---- Don't forget the semicolon


// Use the "class" keyword
class derived : public A, public B
{
    derived(int a, int b) : A(a, b), B(a, b, 0) // <---- for instance
    {

    }

    derived(int a, int b, int c) : B(a, b, c), A(a, b) // <---- for instance
    {

    }
};  // <---- Don't forget the semicolon

【讨论】:

    【解决方案2】:

    A 类和 B 类都没有默认构造函数,您需要在派生构造函数中显式初始化 A 和 B 构造函数。您未能在每个派生构造函数中初始化 A 或 B 构造函数:

    derived(int a, int b):A(a, b), B(a, b, 0) 
                                   ^^^
    {
    }
    
    derived(int a, int b, int c):A(a, b), B(a, b, c)
                                 ^^^
    {
    }
    

    【讨论】:

      【解决方案3】:

      您的第一个派生 ctor 调用 A 的 ctor 而不是 B 的 ctor,因此编译器尝试调用 B 的默认构造函数,该构造函数不存在。

      第二个派生的ctor也是一样的,但是切换A和B。

      解决方案:为 A 和 B 指定默认 ctor。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-31
        • 2018-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-25
        • 1970-01-01
        相关资源
        最近更新 更多