C++ 继承、接口(interface)

标签 c++ inheritance interface

假设我确实有一个接口(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/

相关文章:

interface - 你如何在 Rust 中声明一个接口(interface)?

c++ - 在C++中将默认参数值放在哪里?

c++ - C++ 中的返回数组

C++ "' 形状' : cannot instantiate abstract class"can't find the source of the problem

visual-studio-code - 关闭 VS Code 后如何找到欢迎屏幕?

c# - 定义构造函数签名的接口(interface)?

c++ - 如何从鼠标处理程序中调用成员函数?

c++ - 调用函数时栈上有什么?

c++ - 通过对基类的引用调用虚函数

c# - C#中基类的 `using`指令是否被子类继承?