C++构造函数,参数带默认值

来源:百度知道 编辑:UC知道 时间:2024/05/16 06:31:39
#include<iostream.h>
class ABC{
public:
ABC( int I=1 )
{ cout<<"Constructing ABC with "<< I <<endl; }
~ABC( )
{ cout<<"Distructung ABC"<<endl; }
};

class XYZ: public ABC{
public:
XYZ ( int I=5 ) : ABC( I+1 ){ cout<<"Constructing XYZ with "<< I <<endl; }
~XYZ( ){ cout<<"Distructung XYZ "<<endl; }
};
ABC obj1(3);
void main( )
{
XYZ obj2;
}

老师给的答案是:
Constructing ABC with 3
Constructing ABC with 8
Constructing XYZ with 7
Distructung XYZ
Distructung ABC
Distructung ABC

请问这是为什么啊??? 结果是怎么来的? 构造函数里面参数的默认值是怎么回事? 主要讲下结果就可以了....
谢谢

Constructing ABC with 3 //语句ABC obj1(3);调用类ABC构造函数,创建obj1对象,调用函数时有实参,用I=3代替默认实参I=1
Constructing ABC with 6 //语句XYZ obj2; 调用类XYZ构造函数,先调用ABC(i+1)构造子对象,即先调用类ABC构造函数
Constructing XYZ with 5 //语句XYZ obj2; 调用类XYZ构造函数,先创建子对象完成,调用自身构造函数
Distructung XYZ //调用XYZ析构函数,调用析构函数和调用构造函数顺序相反,构造函数顺序为ABC,ABC,XYZ;析构函数顺序XYZ,ABC,ABC
Distructung ABC //调用ABC析构函数
Distructung ABC //调用ABC析构函数

Constructing ABC with 3
Constructing ABC with 6
Constructing XYZ with 5
Distructung XYZ
Distructung ABC
Distructung ABC
这个才是正确结果
构造函数默认参数原理和规则与普通函数带默认参数是一样的,必须放在参数表后面,当调用时如果缺省就用默认值