析构函数
#include<iostream>using namespace std;
class MyClass
{
public:
MyClass()
{
x=0;
cout<<"default constructor of MyClass called!"<<endl;
}
MyClass(int i)
{
x=i;
cout<<"Constructor of MyClass called! ("<<x<<")"<<endl;
}
~MyClass()
{
cout<<"Destructor of MyClass called! ("<<x<<")"<<endl;
}
int GetX()
{
return x;
}
void Print()
{
cout<<x<<endl;
}
private:
int x;
};
class ExamClass
{
public:
ExamClass()
{
val=0;
cout<<"Default constructor of ExamClass called!"<<endl;
}
ExamClass(int i,int j,int k)/*:member_obj2(k),member_obj1(j)*/
{
member_obj2=k;
member_obj1=j;//为什么将上面注释的部分改为这两行后,在程序没有结束就会调用析构函数呢?
val=i;
cout<<"constructor of ExamClass called!("<<val<<")"<<endl;
}
~ExamClass()
{
cout<<"Destructor of ExamClass called!("<<val<<")"<<endl;
}
void Print()
{
cout<<val<<","<<member_obj1.GetX()<<","<<member_obj2.GetX()<<endl;
}
private:
MyClass member_obj1,member_obj2;
int val;
};
int main()
{
ExamClass obj1,obj2(1,2,3);
system("pause");
obj2.Print();
system("pause");
return 0;
}
问题为上面注释的中文说明处,还有麻烦说明下析构函数是何时被调用的?谢谢
[ 本帖最后由 jfckpep 于 2011-7-21 14:46 编辑 ]