本文共 1496 字,大约阅读时间需要 4 分钟。
目录
继承(inheritance)机制是面向对象程序设计使代码可以复用的最重要的手段,它允许程序员在保 持原有类特性的基础上进行扩展,增加功能,这样产生新的类,称派生类。继承呈现了面向对象 程序设计的层次结构,体现了由简单到复杂的认知过程。以前我们接触的复用都是函数复用,继承是类设计层次的复用。
上代码
class Person{public: void Print() { cout << "name:" << _name << endl; cout << "age:" << _age << endl; }protected: string _name = "peter"; // 姓名 int _age = 18; // 年龄};class Student : public Person{protected: int _stuid; // 学号};class Teacher : public Person{protected: int _jobid; // 工号};int main(){ Student s; Teacher t; s.Print(); t.Print(); return 0;}
运行结果
结论:Student和Teacher复用了Person的成员
1.派生类对象 可以赋值给 基类的对象 / 基类的指针 / 基类的引用。这里有个形象的说法叫切片 或者切割。寓意把派生类中父类那部分切来赋值过去。
2.基类对象不能赋值给派生类对象。
int main(){ Student s; //派生类对象 可以赋值给 基类的对象 / 基类的指针 / 基类的引用。 Person p = s; Person* p = &s; Person& p = s; return 0;}
1. 在继承体系中基类和派生类都有独立的作用域。
2. 子类和父类中有同名成员,子类成员将屏蔽父类对同名成员的直接访问,这种情况叫隐藏, 也叫重定义。(在子类成员函数中,可以使用 基类::基类成员 显示访问)
3. 需要注意的是如果是成员函数的隐藏,只需要函数名相同就构成隐藏。
// Student的_num和Person的_num构成隐藏关系,可以看出这样代码虽然能跑,但是非常容易混淆class Person{protected: int _num = 111;};class Student : public Person{public: void Print() { cout << " 学号:" << Person:: _num << endl;//Person中的num cout << " 学号:" << _num << endl;//Student中的num }protected: int _num = 999; // 学号};void Test(){ Student s1; s1.Print();};int main(){ Test(); return 0;}
// B中的fun和A中的fun不是构成重载,因为不是在同一作用域// B中的fun和A中的fun构成隐藏,成员函数满足函数名相同就构成隐藏。class A{public: void fun() { cout << "func()" << endl; }};class B : public A{public: void fun(int i) { A::fun(); cout << "func(int i)->" <<
转载地址:http://qvqcuy.baihongyu.com/