我想从“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;
}
我该如何解决这个问题?
这是使用组合而非继承解决的主要问题之一。
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;
}