gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:15:15 24 4
gpt4 key购买 nike

来自 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com