c++ - 如何在运行时组合中更改成员对象?

标签 c++ oop composition

来自 Thinking in C++ Vol. 1 (P-33):

Composition comes with a great deal of flexibility. The member objects of your new class are usually private, making them inaccessible to the client programmers who are using the class. This allows you to change those members without disturbing existing client code.
You can also change the member objects at runtime, to dynamically change the behavior of your program. Inheritance, which is described next, does not have this flexibility since the compiler must place compile-time restrictions on classes created with inheritance.

我们如何在运行时更改组合中的成员对象?
写类声明的时候不是包含了对象吗?

类车
{
私有(private):
引擎对象;
}

因此,这里类 car 包含类 engine 的对象。我们如何在运行时更改它?

还是我漏掉了什么?

最佳答案

尝试使用指向您的成员对象的指针:

class car {
    engine *obj;
}

现在您可以在运行时选择是否使用 rotary_enginev8_engineflux_capacitor_engine 的实例。

当然,您可能希望使用类似 unique_ptrshared_ptr 的东西来管理成员对象的所有权和生命周期。

关于c++ - 如何在运行时组合中更改成员对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13899310/

相关文章:

c++ - 帮助在 Visual C++ Express 中进行链接

c++ - 如何通过多个子构造函数正确地将字符串传递给父级。 C++

javascript - ExtJS (JavaScript) 模块设计模式最佳实践

python - 属性错误 : Class Instance has no __call__ method

c# - 在c#中,类型是否可以将其成员类型的接口(interface)公开为自己的接口(interface)

domain-driven-design - 微服务和服务组合中的规范化或非规范化数据

java - 封装在Java模型类中

c++ - 函数定义未在模板中声明参数错误

c++ - kIOReturnNotPermitted 从 IOServiceOpen 连接到 SystemExtension IOService

使用文字创建 Javascript 对象与自定义构造函数