C++编程思想 第1卷 第14章 继承和组合 组合与继承的选择

无论组合还是继承都能把子对象放在新类型中

组合通常是在希望新类内部具有已存在类的功能时使用,而不是希望已存在
类作为它的接口

有时,希望允许类用户直接访问新类的组成,这就让成员对象是public
由于成员对象使用自己的访问控制,所以是安全的

//: C14:Car.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Public composition

class Engine {
public:
  void start() const {}
  void rev() const {}
  void stop() const {}
};

class Wheel {
public:
  void inflate(int psi) const {}
};

class Window {
public:
  void rollup() const {}
  void rolldown() const {}
};

class Door {
public:
  Window window;
  void open() const {}
  void close() const {}
};

class Car {
public:
  Engine engine;
  Wheel wheel[4];
  Door left, right; // 2-door
};

int main() {
  Car car;
  car.left.window.rollup();
  car.wheel[0].inflate(72);
} ///:~

因为Car的组合是分析这个问题的一部分,所以让成员是public,有助于客户
程序员理解如何使用这个类,而且能使类的实例具有更小的代码复杂性

车辆对象组合一个Car是毫无意义的--小汽车不能包含车辆,小汽车本身是
一种车辆。 这种is-a关系用继承表达,而has-a关系用组合表达
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值