visual C++/MFC多重继承调用基类构造函数

visual C++ / MFC multiple inheritance calling base class constructor

本文关键字:调用 基类 构造函数 多重继承 MFC C++ visual      更新时间:2023-10-16

我得到错误C2512:"派生的":在派生的类的构造函数定义中都没有合适的默认构造函数。我的代码如下。我该如何解决这个问题?

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)
    {
    }
}

其中一个问题是,在每个派生类的构造函数中,您只将适当的构造函数参数转发到两个基类中的一个。它们都没有默认构造函数,因此需要显式地为基类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

类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)
                             ^^^
{
}

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

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

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