5
可能重复:
Default constructor and virtual inheritance虚拟继承和参数化的构造函数
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”变成垃圾。关于如何处理它的任何想法?使用参数化构造函数可以解决菱形图案吗?
你错过;“论派生类 – cppguy
@cppguy - 我看不到它,但它不是真正的代码反正(可能只是一个错字)。 –
@MaciejStachowski ildjarn为你添加它 –