#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是一個隨機值,也就是垃圾值。