C ++继承&组成一起使用 [英] C++ Inheritance & composition used together

查看:142
本文介绍了C ++继承&组成一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类A,有更新B的属性的方法。所以,我需要继承。

  class B {
public:
int x;
};

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

我还想通过类B到达函数update,所以我也需要组合。 p>

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

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

我想要我的结构,所以我想跟踪对象的属性 - 类型Bs这种方式:

  ... 
Baupdate(5);
int n = B.x;但是,在声明类A之前,我不能使用组合,并且在声明类B之前不能使用继承。什么是类B?我应该如何解决这个无限循环?

解决方案

我不知道你究竟想实现这里,正确猜测,你可能需要的是一个虚拟函数:

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

class A:public B {
public:
virtual void update(int x){
//这里是B类的代码。
B :: update(x);
//或here;)
}
};

btw,你可能不想要 int B field中的 public:部分;如果您从更新方法修改它的值,您可能不希望其他人尝试直接修改它。


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 ++继承&组成一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆