gpt4 book ai didi

c++ - 虚拟继承和参数化构造函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:44:58 26 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
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”变成了垃圾。关于如何处理它的任何想法?甚至可以使用参数化构造函数解决菱形图案吗?

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com