首页 > 代码库 > c++——继承类中的子对象和基类对象的初始化

c++——继承类中的子对象和基类对象的初始化

先给结论:

(1)派生类中的基类子对象和子对象必须初始化,初始化在派生类的构造函数的初始化列表中,如果初始化列表中没有进行初始化,则调用缺省的构造函数进行初始化。
(2)派生类构造函数的调用顺序:
   基类的构造函数
   子对象类的构造函数
   派生类的构造函数

例子

class point1  
{
public:
 point1();
 point1(int i);
 virtual ~point1();
private:
  int x;   
};
point1::point1()
{
   x=1;
   cout<<"point1's default constructor called!\n";
}
point1::point1(int i)
{ 
 x=i;
    cout<<"point1's  constructor called!\n";
}
point1::~point1()
{
}
 
 
class point2 : public point1  
{
public:
 point2();
 point2(int i,int j,int k);
 virtual ~point2();
 point1 p;
};
point2::point2() 
{
    cout<<"point2's defaule constructor called\n";
}
point2::point2(int i,int j,int k)
{
 cout<<"point2's constructor called\n";
}
point2::~point2()
{
}
 
 
//主函数
void main()
{
   point2 pp;
   point2 pp1(1,2,3);
}


运行结果

point1's default constructor called!// point1 p;调用了基类默认构造函数
point1's default constructor called!//
point2's defaule constructor called
point1's default constructor called!// point1 p;调用了基类默认构造函数
point1's default constructor called!
point2's constructor called

 
如果函数
point2::point2(int i,int j,int k)
{
 cout<<"point2's constructor called\n";
}


改为:
point2::point2(int i,int j,int k):p(j)
{
 cout<<"point2's constructor called\n";
}


运行结果为:
point1's default constructor called!
point1's default constructor called!
point2's defaule constructor called
point1's default constructor called!
point1's  constructor called!
point2's constructor called



c++——继承类中的子对象和基类对象的初始化