十一、继承与组合
1.面向对象编程
2.复合(composition)
(1)表示has-a
(2)Adapter设计模式
queue
deque
(3)composition关系下的构造和析构
Container->Component
构造由内而外
Container的构造函数首先调用component的default构造函数然后才执行自己。
Container::Container(..):Component(){…};
析构由外而内
Container的析构函数首先执行自己,然后才调用Component的析构函数。
Container::~Container(..){…Component()};
红色部分是编译器加的。
3.委托(Delegation)
(1)Composition by reference
指针指向
对象的创建不同步
(2)pimpl(Handle/Body)
指针可以指向不同的实现类
编译防火墙(左边不用再编译,只用编译右边)
Reference counting共享
Copy on write
4.继承(Inheritance)
(1)表示is-a
三种继承方式:最有用的是public
(2)继承关系下的构造和析构
Derived->Base
子类的对象有父类的成分
Base class的dtor必须是virtual,否则会出现undefined behavior。
构造由内而外
Derived的构造函数首先调用Base的default构造函数,然后才执行自己。
Derived::Derived(..):Base(){…};
析构由外而内
Derived的析构函数首先执行自己,然后才调用Base的析构函数。
Derived::~Derived(..){…Base()};
十二、虚函数与多态
1.Virtual
子类继承父类:
继承父类的数据:占用了内存一部分。
继承父类的函数:不从内存角度理解,继承的是调用权,子类可以调用父类的函数。
父类三种函数
Non-virtual函数:你不希望derived class重新定义(override,复写)它。
Virtual函数:你希望derived clss重新定义(override,复写)它,且你对它已有默认定义。
Pure virtual函数:你希望derived clss一定重新定义(override,复写)它,你对它没有默认定义。(其实可以有定义?)
2.Template method
继承with虚函数的一个重要用途:Template method
应用程序框架中,经常用到Template method(模板方法模式,一种设计模式)。
3.inheritance和composition关系下的构造和析构
父类和component的构造谁先谁后?
4.Delegation+inheritance
观察者模式。
十三、委托相关设计
1.Delegation+inheritance
Composite设计模式
2.Delegation+inheritance
Prototype
现在要去创建未来的class,怎么办?
子类自己创建自己
不用clone,用静态函数
静态函数需要class name,但是未来的class不知道class name
Class内部的static成员变量需要在外面定义。