我在派生的类的构造函数定义中得到错误C2512:'derived':没有合适的默认构造函数错误。我的代码如下。我该如何解决这个问题?
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)
{
}
}
答案 0 :(得分:5)
其中一个问题是,在每个派生类的构造函数中,您只将适当的构造函数参数转发给两个基类中的一个。它们都没有默认构造函数,因此您需要为构建基类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
答案 1 :(得分:1)
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)
^^^
{
}
答案 2 :(得分:0)
你的第一个派生的ctor调用A的ctor而不是B的ctor,所以编译器试图调用B的默认构造函数,它不存在。
第二个派生的ctor也是如此,但是转换A和B.
解决方案:为A和B指定默认ctors。