提问人:MANAR Oussama 提问时间:2/20/2023 更新时间:2/20/2023 访问量:53
C++ 多个虚拟继承,类共享同一个子对象
C++ Multiple virtual inheritance, classes share the same subobject
问:
我想从“类 B”继承“x”,从“类 C”继承“y”,但两个类共享同一个“A”子对象。有什么解决办法吗?
#include <iostream>
class A {
protected:
int x;
int y;
public:
A() : x(10), y(10) {}
};
class B : virtual public A {
public:
B() {this->x = 20; this->y = 20;}
};
class C : virtual public A {
public:
C() {this->x = 30; this->y = 30;}
};
class D : public B, public C {
public:
D() {
this->x = this->B::x;
this->y = this->C::y;
std::cout << "x = " << this->x << std::endl;
std::cout << "y = " << this->y << std::endl;
}
};
int main() {
D obj;
return 0;
}
我该如何解决这个问题?
答:
1赞
Fooble
2/20/2023
#1
这是通过使用组合而不是继承来解决的主要问题之一。
https://en.wikipedia.org/wiki/Composition_over_inheritance
D 对象可以包含 B 和 C 的实例,而不是从 B 和 C 继承。请参阅以下示例:
#include <iostream>
class A {
protected:
int x;
int y;
public:
A() : x(10), y(10) {}
int GetX() {
return x;
}
int GetY() {
return y;
}
};
class B : virtual public A {
public:
B() {this->x = 20; this->y = 20;}
};
class C : virtual public A {
public:
C() {this->x = 30; this->y = 30;}
};
class D {
public:
D() {
std::cout << "x = " << this->b.GetX() << std::endl;
std::cout << "y = " << this->c.GetY() << std::endl;
}
private:
B b;
C c;
};
int main() {
D obj;
return 0;
}
评论
B
C
x
y
A
B
C
A