// 测试代码如下
class CTest
{
public:
int m_test;
public:
CTest()
{
cout<<"CTest() m_test = "<<m_test<<endl;
CTest(100);
cout<<"####### m_test = "<<m_test<<endl;
}
CTest(int i) : m_test(i)
{
cout<<"CTest(int i) m_test = "<<m_test<<endl;
}
~CTest()
{
cout<<"~CTest()"<<endl;
}
}
void main()
{
CTest tmp;
cout<<tmp.m_test<<endl;
}
问:为什么最后输出的不是100?
答:main函数中,tmp对象,在调用构造函数CTest()时,其对象本事还未被创建,此默认构造函数中调用另一构造函数CTest(int i),其结果是构造函数CTest(int i)生成一匿名临时对象,并对此对象调用CTest(int i),然后在退出CTest()时,匿名对象被释放。此时tmp对象创建成功,但成员变量并未初始化,cout<<tmp.m_test<<endl;具体输出结果不可知。查看程序上面的构造和析构函数输出即可知。