C++继承&组合使用 [英] C++ Inheritance & composition used together
问题描述
我有类 A,有更新 B 属性的方法.所以,我需要继承.
class B{上市:整数 x;};A类:公共B{上市:无效更新(int y){x = y;}};
我也想通过B类实现update"函数,所以也需要组合.
class B{上市:一个;整数 x;};A类:公共B{上市:无效更新(int y){x = y;}};
我想要这样的结构,以便我想以这种方式跟踪对象类型 B 的属性:
<预><代码>...B.a.update(5);int n = B.x;但是,我不能在声明类 A 之前使用组合,也不能在声明类 B 之前使用继承.我该怎么做才能解决这个无限循环?
我不确定您在这里到底想达到什么目的,但如果我猜对了,您可能需要一个虚函数:
class B{上市:国际B;虚拟无效更新(int x){B = x;}};A类:公共B{上市:虚拟无效更新(int x){//这里是特定于 B 类的代码.B::更新(x);//或这里 ;)}};
顺便说一句,您可能不希望 public:
部分中的 int B
字段;如果您通过 update
方法修改它的值,您可能不希望其他人尝试直接修改它.
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 ?
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.
这篇关于C++继承&amp;组合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!