**继承(Inheritance):**从已存在的类中克隆新的类并扩展
成员限定词 | 同一类内 | 派生类内 | 类外 |
---|---|---|---|
private |
Yes | No | No |
protected |
Yes | Yes | No |
public |
Yes | Yes | Yes |
设类 $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 中不可访问 |
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;
};