- 派生类对象单元中含有基类数据——基类数据可以在基类中初始化
i:派生类构造函数可通过调用基类构造函数完成派生类对象中基类数据成员的初始化
ii:派生类的构造函数体只表示派生类中数据成员的初始化 - 表示:派生类名(总形参):基类名(实参)
{
//派生类构造函数体
};
#include<iostream>
using namespace std;
class Base{
private:
int x,y;
public:
Base(){
x=0;
y=0;
}
Base(int x,int y){
this->x=x;
this->y=y;
}
void Print()
{
cout<<x<<" "<<y<<endl;
}
};
class Derived:public Base{
private:
int z;
public:
Derived()
{
z=0;
}
Derived(int i):Base(i+3,i-1)
{
z=i;
}
void Print()
{
Base::Print();
cout<<z<<endl;
}
};
int main()
{
Derived objD(3);
objD.Print();
return 0;
}
- 派生类构造函数的调用顺序:①调用基类构造
②执行派生类构造函数体 - 释放派生类对象时,要调用析构函数,析构函数的调用严格与构造函数相反
#include<iostream>
using namespace std;
class Base{
private:
int x,y;
public:
Base(){
x=0;
y=0;
cout<<"Base Cons!"<<endl;
}
Base(int x,int y){
this->x=x;
this->y=y;
cout<<"Base Cons!"<<endl;
}
void Print()
{
cout<<"x="<<x<<endl;
cout<<"y="<<y<<endl;
}
~Base()
{
cout<<"Base Des!"<<endl;
}
};
class Derived:public Base{
private:
int z;
public:
Derived()
{
z=0;
cout<<"Derived Cons!"<<endl;
}
Derived(int i):Base(i+3,i-1)
{
z=i;
cout<<"Derived Cons!"<<endl;
}
void Print()
{
Base::Print();
cout<<"z="<<z<<endl;
}
~Derived()
{
cout<<"Derived Des!"<<endl;
}
};
int main()
{
/*Derived objD(3);
objD.Print();*/
Derived *p=new Derived(3);
p->Print();
delete p;
return 0;
}
- 含有子对象的派生类的构造函数表示:
派生类名(总形参):基类名(实参),子对象1(实参),子对象2(实参)…
{
//派生类构造函数体
}; - 派生类构造函数的调用顺序:
调用基类构造函数—》调用子对象构造函数—》执行派生类构造函数体 - 若含有多个子对象,按子对象定义顺序调用构造函数
#include<iostream>
using namespace std;
class Myclass{
public:
Myclass()
{
cout<<"Myclass cons!"<<endl;
}
~Myclass()
{
cout<<"Myclass Des!"<<endl;
}
};
class Yourclass{
public:
Yourclass()
{
cout<<"Yourclass cons!"<<endl;
}
~Yourclass()
{
cout<<"Yourclass Des!"<<endl;
}
};
class Base{
private:
Myclass my;
public:
Base()
{
cout<<"Base cons!"<<endl;
}
~Base()
{
cout<<"Base Des!"<<endl;
}
};
class Derived:public Base{
private:
Myclass objMy;
Yourclass objYour;
Base objBase;
public:
Derived()
{
cout<<"Derived Cons!"<<endl;
}
~Derived()
{
cout<<"Derived Des!"<<endl;
}
};
int main()
{
Derived *p=new Derived();
delete p;
return 0;
}