一、组合 Composition

  1. **组合(Composition):**将类 $A$ 的对象作为类 $B$ 的成员,包含两种方式:
  2. 完全包含

二、继承 Inheritance

**继承(Inheritance):**从已存在的类中克隆新的类并扩展

1. 基类成员的访问权限

成员限定词 同一类内 派生类内 类外
private Yes No No
protected Yes Yes No
public Yes Yes Yes

2. 继承方式与访问权限

设类 $A$ 为基类,类 $B$ 为派生类

B 的继承方式 A 的 public 成员 A 的 protected 成员 A 的 private 成员
B: private A private in B private in B B 中不可访问
B: protected A protected in B protected in B B 中不可访问
B: public A public in B protected in B B 中不可访问

3. 派生类的构造与析构

class Employee{
public:
	Employee(const string& name);
	const string& get_name() const { return m_name; }
	void print(ostream& out) const { out<<m_name<<endl; }
	void print(ostream& out, const string& msg) const
	{ out<<msg<<endl; print(out); }
	
protected:
	string m_name;
};

class Manager: public Employee{
public:
	Manager(const string& name, const string& title = "")
	: Employee(name) {}
	const string& get_title() const { return m_title; }
	void print(ostream& out) const { out<<m_name<<m_title<<endl; }
	
private:
	string m_title;
};

4. 友联 Friends