可能重复:
默认构造函数和虚拟继承
class Base
{
private:
int number;
protected:
Base(int n) : number(n) {}
public:
virtual void write() {cout << number;}
};
class Derived1 : virtual public Base
{
private:
int number;
protected:
Derived1(int n, int n2) : Base(n), number(n2) {}
public:
virtual void write() {Base::write(); cout << number;}
};
class Derived2 : virtual public Base
{
private:
int number;
protected:
Derived2(int n, int n2) : Base(n), number(n2) {}
public:
virtual void write() {Base::write(); cout << number;}
};
class Problematic : public Derived1, public Derived2
{
private:
int number;
public:
Problematic(int n, int n2, int n3, int n4) : Derived1(n, n2), Derived2(n, n3), number(n4) {}
virtual void write() {Derived1::write(); Derived2::write(); cout << number;}
};
int main()
{
Base* obj = new Problematic(1, 2, 3, 4);
obj->write();
}
换句话说:
Base
| \
| \
| \
| \
D1 D2
| /
| /
| /
| /
Problematic
我试图在输出中获得“1 2 1 3 4”。然而,编译器一直抱怨我在 Base 中需要一个无参数构造函数,但是当我添加一个时,“1”变成了垃圾。关于如何处理它的任何想法?甚至可以使用参数化构造函数来解决菱形图案吗?