#include <iostream>
using namespace std;
class Test
{
private:
int m_a;
int m_b;
int m_c;
public:
Test(int a, int b, int c);
Test(int a, int b);
int GetC();
~Test();
};
Test::Test(int a, int b, int c)
{
cout << "Test Constructor3" << endl;
m_a = a;
m_b = b;
m_c = c;
}
Test::Test(int a, int b)
{
cout << "Test Constructor2" << endl;
m_a = a;
m_b = b;
Test(a, b, 3);
}
int Test::GetC()
{
return m_c;
}
Test::~Test()
{
cout << "Test Destruct" << endl;
}
int main()
{
Test t(1, 2);
cout << "c : " << t.GetC() << endl;
return 0;
}
答案:
Test Constructor2
Test Constructor3
Test Destruct
c=10235892
Test Destruct
程序先是根据参数选择合适的构造函数,当调用两个参数的构造函数时,又运行了三个参数 的构造函数,但是这只是临时的匿名变量,生命周期只是在那一句话的运行时间里,一旦运行下一句,就会释放内存(也就是调用析构函数)。同时对c的赋值也是给了那个临时变量,并不是给了对象t,所以t的数据成员m_c是一个随机值,也就是垃圾值。