假设我确实有一个接口(interface) IControllable
,3 个类继承了该接口(interface):MachineControllable、LightControllable、OtherControllable
,它们具有一些特定的数据和方法。
现在我确实只想拥有所有 IControllable
的一个容器,因此我创建了一个 vector 容器。
vector<IControllable> allControllables; // and put all the MachineControllable,
//LightControllable, OtherControllable here by the IControllable interface class.
但现在的问题是,我只能使用IControllable
定义的内容,而不能使用特定Controllable的具体数据和方法。
我是否应该为每个 Controllable 提供单独的容器,或者我的逻辑在 OOP 方面是错误的?
最佳答案
"Should I have seperate containers for each Controllable, or how my logic is wrong in terms of OOP ?"
不,你的逻辑没问题。问题是,您无法实例化抽象类。
您应该有一个容器来保存指向 IControllable
接口(interface)的指针,例如:
vector<IControllable*> allControllables;
或
vector<std::unique_ptr<IControllable>> allControllables;
或
vector<std::shared_ptr<IControllable>> allControllables;
关于C++ 继承、接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30695839/