考察下面的程序:
class point1
{
public:
point1();
point1(int i);
virtual ~point1();
private:
int x;
};
{
public:
private:
};
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()
{
{
}
point1::point1(int i)
{
}
point1::~point1()
{
}
class point2 : public point1
{
public:
point2();
point2(int i,int j,int k);
virtual ~point2();
point1 p;
};
{
public:
};
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(int i,int j,int k)
{
}
point2::~point2()
{
{
}
//主函数
void main()
{
point2 pp;
point2 pp1(1,2,3);
}
{
}
运行结果
point1's default constructor called!
point1's default constructor called!
point2's defaule constructor called
point1's default constructor called!
point1's default constructor called!
point2's constructor called
point1's default constructor called!
point2's defaule constructor called
point1's default constructor called!
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
point1's default constructor called!
point2's defaule constructor called
point1's default constructor called!
point1's
point2's constructor called
结论:
(1)派生类中的基类子对象和子对象必须初始化,初始化在派生类的构造函数的初始化列表中,如果初始化列表中没有进行初始化,则调用缺省的构造函数进行初始化。
(2)派生类构造函数的调用顺序:
1.1 所有虚基类的构造函数按照它们被继承的顺序构造
1.2 所有非虚基类的构造函数按照它们被继承的顺序构造