C/C++教程

C++继承

本文主要是介绍C++继承,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

继承语句

class 派生类 : 基类名表 {

};

其中基类名表格式是:

访问控制 基类名1 , 访问控制 基类名2 , ...
  1. 可以省略访问描述符,默认是私有继承;

访问控制

  1. public 继承:public -> public , private 不可访问 , protected -> protected
  2. protected 继承:public -> protected , private 不可访问 , protected -> protected
  3. private 继承:public -> private , private 不可访问 , protected -> private

继承和包含关系下的构造析构顺序

  1. 基类的属性
  2. 基类的构造方法
  3. 派生类的属性
  4. 派生类的构造方法

如果上面的属性是类对象,参照上一篇博文的构造顺序。如果继承多个基类,按照声明的顺序构造基类,每个基类分别定义属性,执行构造方法之后才到下一个基类

#include<iostream>
using namespace std;

class Inter{
    string name;

public:
    Inter(){
        name = "inter";
        cout<<name<<" of Inter build!"<<endl;
    }
    Inter(string n){
        name = n;
        cout<<"Inter use "<<n<<" build!"<<endl;
    }
    ~Inter(){
        cout<<name<<" of Inter not build!"<<endl;
    }
};

class InterPlus{
    string name;

public:
    InterPlus(){
        name = "interplus";
        cout<<name<<" of InterPlus build!"<<endl;
    }
    InterPlus(string n){
        name = n;
        cout<<"InterPlus use "<<n<<" build!"<<endl;
    }
    ~InterPlus(){
        cout<<name<<" of InterPlus not build!"<<endl;
    }
};

class Base{
    InterPlus itp;
public:
    Base():itp("itp"){
        cout<<"Base build!"<<endl;
    }
    ~Base(){
        cout<<"Base not build!"<<endl;
    }
};

class BasePlus{
public:
    BasePlus(){
        cout<<"BasePlus build!"<<endl;
    }
    ~BasePlus(){
        cout<<"BasePlus not build!"<<endl;
    }

};

class Detrived:Base,BasePlus{
    Inter it;

public:
    Detrived(){
        cout<<"Detrived build!"<<endl;
    }
    ~Detrived(){
        cout<<"Detrived not build!"<<endl;
    }
};

int main(){
    Detrived d;
}
结果:
InterPlus use itp build!
Base build!
BasePlus build!
inter of Inter build!
Detrived build!
Detrived not build!
inter of Inter not build!
BasePlus not build!
Base not build!
itp of InterPlus not build!

分析:

  1. 想要创建 Detrived 对象,需要先创建 Base 和 BasePlus 对象,先 Base 再 BasePlus;
  2. 先创建 Base 对象,先定义 Base 的属性,是一个 InterPlus 对象,先创建 InterPlus 对象,看 Base 构造函数的初始式有 InterPlus(string n) 构造方法,调用这个构造方法,输出第 1 句
  3. 然后执行 Base 的构造函数,输出第 2 句
  4. 然后创建 BasePlus 对象,没有属性,直接执行构造函数,输出第 3 句
  5. 然后创建 Detrived 对象,先定义属性,是一个 Inter 类对象,默认函数构造 Inter 对象,直接调用构造函数,输出第 4 句
  6. 然后执行 Detrived 构造函数,输出第 5 句
  7. 按照上面构造的逆序执行析构函数。

访问声明

继承关系使基类成员(属性和方法)在派生类中是固定的,如私有继承下,基类的 ptotected 到派生类变成了 private,为了更加灵活地控制访问权限(如将其改为 protected 权限),引入访问声明,其语法是:在派生类中想要将基类的成员改到目标的访问域中加上声明

基类::成员;
  1. 访问声明仅调整名字的访问权限;
  2. 访问声明不允许在派生类中降低或升高可访问性,如上面的不能改为 public 和 private;
  3. 基类的私有成员在派生类根本不可见,也不能用于访问声明;
  4. 对基类重载函数名的访问声明会调整基类所有同名函数的访问域;但是基类的重载函数不在同一访问域不能进行访问声明,派生类和基类名字相同的成员不可调整访问权限。

在 C++ 11 中,访问声明已经被弃用。

重名成员

这篇关于C++继承的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!