侯捷老师P11 复合、委托、继承 类与类之间的三大关系, 复合、委托、继承(C++)

侯捷老师P11 复合、委托、继承 https://www.bilibili.com/video/av19038490/?p=11

// 类与类之间的三大关系

// ------------------1.compsiton(复合)----------------------
// 可用于Adapter(适配器模式):把一个类的接口变换成客户端所期待的另一种接口,
// 		从而使原本因接口原因不匹配而无法一起工作的两个类能够一起工作。
//		适配类可以根据参数返还一个合适的实例给客户端。
// 类的定义中包含其他类对象   container(queue) --- component(deque)
// 构造由内而外,
// container::container(...): component() {...};
// container的构造函数 首先调用component的default构造函数,然后才执行自己
// 编译器默认添加component(),调用的是默认构造函数。如果需要自定义就要像上面一样 写出来并指定合适的参数
// 析构由外向内,
// container::~container(...) { ... ~component(); }
// container的析构函数首先执行自己,然后才component得析构函数
// 生命周期同步(同时创建消失)

// sizeof: 40
template<class T>
class queue{
protected:
  deque<T> c;
};

// sizeof: 16*2 + 4 + 4
template<class T>
class deque{
protected:
  Itr<T> start;
  Itr<T> finish;
  T** map;
  unsigned int map_size;
};

// sizeof: 4 * 4
template<class T>
struct Itr{
  T* cur;
  T* first;
  T* last;
  T** node;
}; 


// ------2.delegation(委托) [composition by reference]------Handle/Body(pImpl)
// 指针相连
class StringRep;
class String{
public:
  String();
  String(const char* s);
  String(const String& str); // 拷贝构造
  String& operator= (const  String& s); // 拷贝赋值   
  ~String();
private:    
  // 只提供接口,具体实现在外部,外部变动不影响这里
  StringRep* rep; // handle  [composition by reference] point to implement-pimpl
};

class StringRep{    // body
friend class String;
  StringRep(const char* );
  ~StringRep();
  int count;
  char* rep;
};


// --------------------3.inheritance(继承)---------------------
// c++有三种继承方式:public  private  protected

// public继承方式
// 父类的数据是被完整的继承下来

// 构造由内向外,
// Derived::Derived(...) Base() {...};
// Derived的构造函数首先调用Base的default构造函数,然后才执行自己。
// 
// 析构由外向内,
// Derived::~Derived(...) {... ~Base();};
// Derived的析构函数首先执行自己,然后才调用base的析构函数
// 
// Base class的析构函数必须是virtual,否则出现undefined behavior,
// 当设计的类会被继承,必须设计其析构函数类型为virtual

struct _List_node_base
{
  _List_node_base* _M_next;
  _List_node_base* _M_prev;
};

// _List_node继承自_List_node_base
// 父类的数据是被完整的继承下来,_List_node除了_M_data之外还有父类的两个指针数据
template<typename _Tp>
struct _List_node
  : public _List_node_base
{
  _Tp _M_data;
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值