来自 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_engine
或 v8_engine
或 flux_capacitor_engine
的实例。
当然,您可能希望使用类似 unique_ptr
或 shared_ptr
的东西来管理成员对象的所有权和生命周期。
关于c++ - 如何在运行时组合中更改成员对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13899310/