visual C++/MFC多重继承调用基类构造函数
visual C++ / MFC multiple inheritance calling base class constructor
我得到错误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)
{
}
}
其中一个问题是,在每个派生类的构造函数中,您只将适当的构造函数参数转发到两个基类中的一个。它们都没有默认构造函数,因此需要显式地为基类A
和B
的构造提供参数。
第二个问题是基类的构造函数被隐式声明为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。
相关文章:
- 使用基类指针调用基类的值构造函数的语法是什么?
- 在初始化列表之外手动调用基类的构造函数
- 继承:调用基类的成员和方法
- 在成员构造函数之后调用基类构造函数
- C++初始化之前派生类调用基类的方法
- 如何在具有相同函数名称的派生类中调用基类的函数
- 有没有办法在C++中调用基类的所有子类函数?
- C++:在派生类成员上调用基类方法
- 添加字符串类型的类成员会导致调用基类函数而不是子函数
- 有没有办法调用基类函数,该函数在使用私有继承的派生类中被覆盖?
- 如何在C++中调用基类虚函数
- 如何让派生类在调用基类之前执行操作?
- 在调用基类之前需要在成员上调用方法
- 调用基类克隆实现
- 在派生类中调用基类方法,而无需指定基类名称
- 从参数包中派生的调用基类运算符 =
- 当应该调用派生类方法时,为什么要调用基类方法
- 调用基类函数时强制使用类名?
- 无法从派生的一个方法调用基类方法
- 当派生类无法轻易将参数传递到基类时,如何调用基类构造函数