如何设计下面的类继承
How to design the following class inheritance?
本文关键字:继承 更新时间:2023-10-16
我面临着类继承设计的问题。在c++ 中显示如下:
有两类,我们先称它们为Object
和Component
。Object
类使用Component
类,但它们的子类出现问题。
对于simple,有6个类。
class BaseComponent{...};
class ComponentA: public BaseComponent{...};
class ComponentB: public BaseComponent{...};
class BaseObject {
public:
virtual bool doSomething()=0;
void setBaseComponent(BaseComponent*c){_c = c;}
BaseComponent* getBaseComponent() {return _c;}
private:
BaseComponent* _c;
}
class ObjectA : public BaseObject {
public:
bool doSomething(){ /*do someting related to ComponentA*/}
void setComponentA(ComponentA* a) {setBaseComponent(a);}
ComponentA* getComponentA()
{return static_cast<ComponentA*>(getBaseComponent());}
}
class ObjectB : public BaseObject {
public:
bool doSomething(){ /*do someting related to ComponentB*/}
void setComponentB(ComponentB* b) {setBaseComponent(b);}
ComponentB* getComponentB()
{return static_cast<ComponentB*>(getBaseComponent());}
}
现在问题来了:
如果我喜欢上面的代码,我必须总是检查类关系。
(例如,当使用static_cast
时,我必须检查ObjectB::getComponentB()
中的真实类)
如果我更改代码并在ObjectA
中直接使用ComponentA
,我就放弃了"依赖倒置",这使得代码不方便。那么,谁能给我一些建议呢?
所以BaseObject
的任何子类总是需要匹配的BaseComponent
子类?
设置BaseObject
中的setter为protected。它声称你可以给任何对象任何组件,如果除了它们之外的任何人都可以访问那个setter,那么子类就不能遵守这个承诺。
如果可能的话,将组件作为构造函数的参数会更好。
使用接口而不是具体类的想法是,当你使用接口的指针时,你不必担心后面是什么。
如果你返回具体的ComponentA
和ComponentB
,那么你失去了它。
然后,在我看来,您应该更改这些具体类,以便能够返回BaseComponent
的指针,然后您将不需要static_cast。
相关文章:
- 继承函数的重载解析
- 继承期间显示未知行为的子类
- 头文件-继承c++
- 为什么在保护模式下继承升级不起作用
- 通过继承类使用来自不同命名空间的运算符
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 混合组合和继承的C++问题
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 从类继承时,继承的类是否会通过父类重新定义继承的变量
- 公共与私人继承
- 如何创建从同一类继承的不同对象的向量
- 如何从另一个文件继承私有成员变量和公共函数
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 带有继承的C++工厂
- 我应该避免多重实现继承吗
- C++继承更改成员
- 从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明
- 关于C++中具有多重继承"this"指针的说明
- 尝试使用继承和模板实现CRTP.Visual Studio正在生成编译器错误
- 如何在QT Creator上将QWidget声明为继承类的对象