Compostion(复合),has-a
Adapter
template<class T>
class queue{
...
protected:
deque<T> c; //底层容器
public:
//以下完全利用c的操作函数完成
bool empty() const {return c.empty();}
size_type size() const {return c.size();}
reference front() {return c.front();}
reference back() {return c.back();}
//
void push(const value_type& x) {c.push_back(x);}
void pop() {c.pop_front();}
};
Compositon(复合)关系下的构造和析构
构造由内而外
Container的构造函数首先调用Component的default构造函数,然后在执行自己
Container::Container(...):Component() {...};
注:Component是编译器调用
析构由外而内
Container的析构函数首先执行自己,然后才调用Component的析构函数
Container::~Container(...) {... ~Component() };
Delegation(委托),Composition by reference
class StringRep;
class String{
public:
String();
String(const char* s);
String(const String& s);
String &operator=(const String& s);
~String();
//...
private:
StringRep* rep;//pimpl
};
class StringRep{
friend class String;
StringRep(const char* s);
~StringRep();
int count;
char* rep;
};
PIMPL模式
Inheritance(继承),表示is-a
struct _List_node_base
{
_List_node_base* _M_next;
_List_node_base* _M_prev;
};
template<typename _Tp>
struct _List_node : public _List_node_base
{
_Tp _M_data;
};
Inheritance(继承)关系下构造和析构
base class的dtor必须是virtual,否则会出现undefined behavior
构造由内而外
Derived的构造函数首先调用Base的default构造函数,然后再执行自己
Derived::Derived(...) : Base() {...};
析构由外而内
Derived的析构函数首先执行自己,然后才调用Base的析构函数
Derived::Derived(...) { .... ~Base() };