C++ 構造函數


#include <iostream>

using namespace std;

class Test
{
public:
	Test(int n) 
	{
		cout << "1" << endl;
	}
	Test(int n, int m) 
	{
		cout << "2" << endl;
	}
	Test() 
	{
		cout << "3" << endl;
	}
};

int main()
{
	Test array1[3] = { 1, Test(1,2) };
	Test array2[3] = { Test(2,3), Test(1,2),1 };

    Test *pArray1[3];
	Test *pArray2[3] = { new Test(1,2), new Test(2)};
    Test *pArray3[3] = { &Test(1), &Test(1,2)};
       return 0;
}

創造對象的時候都會執行構造函數。

對於指針,只聲明指針時並不會執行構造函數,如pArray1;

                   聲明指針並用new分配或者指定對象地址時,就會執行構造函數,如 pArray2, pArray3。

發佈了94 篇原創文章 · 獲贊 19 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章