C++ Inheritance & composition used together

≯℡__Kan透↙ 提交于 2019-12-25 10:51:09

问题


I have class A, having methods that update properties of B. So, I need inheritance.

class B{
public:
int x;
};

class A : public B{
public:
void update(int y){
x = y;
}
};

I also want to reach function "update" through class B, so I also need composition.

class B{
public:
A a;
int x;
};

class A : public B{
public:
void update(int y){
x = y;
}
};

I want my structure as such, so that I want to track properties of objects-type Bs this way:

...
B.a.update(5);
int n = B.x;

However, I cannot use composition before declaring class A, and cannot use inheritance before declaring class B. What should I do to resolve this infinite loop ?


回答1:


I am not sure what exactly you are trying to achieve here, but if I'm guessing correctly, what you might need is a virtual function:

class B{
public:
int B;
virtual void update(int x){
    B = x;
}
};

class A : public B{
public:
virtual void update(int x){
    // Here goes code specific to B-class.
    B::update(x);
    // or here ;)
}
};

btw, you probably don't want int B field in a public: section; if you modify it's value from update method, you probably don't want others to try to modify it directly.



来源:https://stackoverflow.com/questions/17327081/c-inheritance-composition-used-together

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!