1.派生类的构造函数
派生类中有基类中说明的数据成员应该由基类中的构造函数进行初始化。如果派生类中还有子对象的时候,还应包含对子对象初始化的构造函数。
#include<iostream>
using namespace std;
class A{
public:
A(){
a=0;
cout<<"A's default constructor called"<<endl;
}
A(int i){
a=i;
cout<<"A's constructor called"<<endl;
}
~A(){
cout<<"A's destructor called"<<endl;
}
void Print() const{
cout<<a<<",";
}
int Geta(){
return a;
}
private:
int a;
};
class B:public A{
public:
B(){
b=0;
cout<<"B's default constructor called"<<endl;
}
B(int i,int j,int k);
~B(){
cout<<"B's destructor called"<<endl;
}
void Print();
private:
int b;
A aa;
};
B::B(int i,int j,int k):A(i),aa(j){
b=k;
cout<<"B's constructor called"<<endl;
}
void B::Print(){
A::Print();
cout<<b<<","<<aa.Geta()<<endl;
}
int main(){
B bb[2];
bb[0]=B(1,2,5);
bb[1]=B(3,4,7);
for(int i=0;i<2;i++){
bb[i].Print();
}
}
2.派生类的析构函数
在执行派生类的析构函数的时候,基类的析构函数也将被调用,先派后基。
#include<iostream>
using namespace std;
class M{
public:
M(){
m1=m2=0;
}
M(int i,int j){
m1=i;m2=j;
}
void print(){
cout<<m1<<","<<m2<<",";
}
~M(){
cout<<"M's destructor called"<<endl;
}
private:
int m1,m2;
};
class N:public M{
public:
N(){
n=0;
}
N(int i,int j,int k);
void print(){
M::print();
cout<<n<<endl;
}
~N(){
cout<<"N's destructor called"<<endl;
}
private:
int n;
};
N::N(int i,int j,int k):M(i,j),n(k){
}
int main(){
N n1(5,6,7),n2(-2,-3,-4);
n1.print();
n2.print();
}