class 派生类 : 基类名表 { };
其中基类名表格式是:
访问控制 基类名1 , 访问控制 基类名2 , ...
如果上面的属性是类对象,参照上一篇博文的构造顺序。如果继承多个基类,按照声明的顺序构造基类,每个基类分别定义属性,执行构造方法之后才到下一个基类。
#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!
分析:
继承关系使基类成员(属性和方法)在派生类中是固定的,如私有继承下,基类的 ptotected 到派生类变成了 private,为了更加灵活地控制访问权限(如将其改为 protected 权限),引入访问声明,其语法是:在派生类中想要将基类的成员改到目标的访问域中加上声明:
基类::成员;
在 C++ 11 中,访问声明已经被弃用。