读书人

派生类构造函数与析构函数的结构规则

发布时间: 2012-08-13 13:21:53 作者: rapoo

派生类构造函数与析构函数的构造规则

1.派生类的构造函数可以不显示式的写出基类的构造函数。例如:

Third()
{e=0;}

此时,系统自动调用基类的无参构造函数(没有,则为默认的构造函数)。也可显示式的指出调用基类的哪一个构造函数。例如:

Third(int x,int y,int z):Second(x,y)
{
e=z;
}

2.要调用的基类构造函数的参数可在派生类的构造函数中明确给出。例如:

Third(int x,int y,int z):Second(x,y)
{
e=z;
}

也可不给出:

Second():First(1,1)
{
c=0;
d=0;
}

还可以对派生类构造函数的参数进行一些交换,再传递给要调用的基类的构造函数,例如:

Second(int x,int y):First(x+1,y+1)
{
c=x;
d=y;
}

一个完整的例子如下:

#include<iostream>using namespace std;class First{public:First(){a=0;b=0;}First(int x,int y){a=x; b=y;}~First(){cout<<"destructing First"<<endl;}void show(){     cout<<"\n a="<<a<<"\n b="<<b<<endl;}private:int a;int b;};class Second:public First{public:Second():First(1,1){c=0;d=0;}Second(int x,int y):First(x+1,y+1){c=x;d=y;}Second(int x,int y,int m,int n):First(m,n){c=x;d=y;}~Second(){cout<<"destructing Second"<<endl;}void show(){First::show();cout<<"c="<<c<<"d="<<d<<endl;}private:int c,d;};class Third:public Second{public:Third(){e=0;}Third(int x,int y,int z):Second(x,y){         e=z;}Third(int x,int y,int z,int m,int n):Second(x,y,m,n){e=z;}~Third(){cout<<"destructing Third"<<endl;}void show(){Second::show();cout<<"e="<<e<<endl;}private:int e;};int main(){First f;f.show();cout<<"======================"<<endl;Second d1;d1.show();cout<<"======================"<<endl;Second d2(10,20,30,40);    d2.show();cout<<"====================="<<endl;Second d3(12,13);d3.show();cout<<"======================="<<endl;Third t;t.show();cout<<"======================"<<endl;Third t1(14,15,16);t1.show();cout<<"======================="<<endl;Third t2(50,60,70,80,90);t2.show();return 0;}


派生类构造函数与析构函数的结构规则

读书人网 >编程

热点推荐