目录
命运给你一个最低的起点,是想看你逆风翻盘的精彩
这里是来自M--Y的专栏:C++启航
以下内容均为个人见解,如有不足还请指出
期待大家的点赞、收藏、评论(互三必回)诸君共勉
1.继承的概念及定义
1.1继承的本质就是代码的复用
class Person
{
……
};
//类Student继承父类Person后,父类的成员都会成为子类的一部分,包括变量和成员函数的复用
class Student : public Person
{
……
}
1.2继承的定义
1.2.1继承的定义格式
上图中Person是父类,也叫做基类,Student是子类,也叫做派生类
1.2.2继承关系和访问限定符
1.2.3继承基类成员访问方式变化
小结:
1.基类private成员,被继承到派生类对象后,在派生类对象的类里面还是类外面都不可访问
2.基类protected成员,被继承到派生类对象后,在派生类内可以访问,在类外不能访问
3.基类public成员,被继承到派生类后,在类内、类外都能访问
2.基类和派生类对象赋值转换
注意:
1.基类对象不能赋值给派生类对象(一般情况下)
2.派生类对象可以赋值给基类对象/基类指针/基类的引用
3.在基类的指针是指向派生类的对象时,基类的指针或者引用可以通过强制类型转换赋值给派生类的指针或者引用
3.继承中的隐藏关系
子类和父类中有同名成员存在,两者间就构成隐藏
//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)->" << i << endl ;}};
4.派生类的默认成员函数
1.派生类的构造函数必须调用基类的构造函数初始化基类的那一部分成员。如果基类没有默认的构造函数,则必须在派生类构造函数的初始化列表内显示调用
2.派生类的开呗构造函数必须调用基类的拷贝构造完成基类的拷贝初始化
3.派生类的operator=必须调用基类的operator=完成基类的复制
4.派生类对象初始化先调用基类构造在调用派生类的构造
5.派生类对象析构清理先调用派生类析构再调用基类析构
class Person{public :Person ( const char* name = "peter" ): _name ( name ){cout << "Person()" << endl ;}Person ( const Person & p ): _name ( p . _name ){cout << "Person(const Person& p)" << endl ;}Person & operator = ( const Person & p ){cout << "Person operator=(const Person& p)" << endl ;if ( this != & p )_name = p . _name ;return * this ;}~Person (){cout << "~Person()" << endl ;}protected :string _name ; // 姓名};class Student : public Person{public :Student ( const char* name , int num ): Person ( name )// 基类构造函数的显示调用, _num ( num ){cout << "Student()" << endl ;}Student ( const Student & s ): Person ( s )// 基类函数的显示调用, _num ( s . _num ){cout << "Student(const Student& s)" << endl ;}Student & operator = ( const Student & s ){cout << "Student& operator= (const Student& s)" << endl ;if ( this != & s ){Person::operator = ( s );_num = s . _num ;}return * this ;}~Student (){cout << "~Student()" << endl ;}protected :int _num ; // 学号};
5.继承与友元
友元关系不能继承,也就是说基类友元不能日访问子类私有和保护成员
6. 继承与静态成员
基类定义了static静态成员,则整个继承体系里面只有一个这样的成员,无论派生出多少个子类,都只有一个static成员实例
class Person{public :Person () { ++ _count ;}protected :string _name ; // 姓名public :static int _count ; // 统计人的个数。};int Person :: _count = 0 ;class Student : public Person{protected :int _stuNum ; // 学号};class Graduate : public Student{protected :string _seminarCourse ; // 研究科目};void TestPerson (){Student s1 ;Student s2 ;Student s3 ;Graduate s4 ;cout << " 人数 :" << Person :: _count << endl ;Student :: _count = 0 ;cout << " 人数 :" << Person :: _count << endl ;}//得到结果:人数:4// 人数:0
由上面的代码可以看出基类和派生类以及派生类的子类用的都是一个_count,改变其中一个另外的也会变。