加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如何在合成中的运行时更改成员对象?

发布时间:2020-12-16 09:41:04 所属栏目:百科 来源:网络整理
导读:从C卷中的思考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
从C卷中的思考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.

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

班车
{
私人的:
引擎obj;
}

所以,这里的类汽车包含类引擎的对象.我们怎样才能在运行时改变它?

还是我错过了一些观点?

解决方法

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

class car {
    engine *obj;
}

现在,您可以在运行时选择是使用rotary_engine还是v8_engine或flux_capacitor_engine的实例.

当然,您可能希望使用unique_ptr或shared_ptr之类的东西来管理成员对象的所有权和生命周期.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读