021_構造函數寫了,就必須用

/*
1)當類中沒有定義任何一個構造函數時,c++編譯器會提供默認無參構造函數和默認拷貝構造函數
2)當類中定義了拷貝構造函數時,c++編譯器不會提供無參數構造函數
3) 當類中定義了任意的非拷貝構造函數(即:當類中提供了有參構造函數或無參構造函數),
   c++編譯器不會提供默認無參構造函數
4 )默認拷貝構造函數成員變量簡單賦值


總結:只要你寫了構造函數,那麼你必須用。

	*/

第一種情況

#if 1
class Test
{
public:
	//第一種情況 不寫任何函數,編譯通過,使用默認的構造函數
	void printT()
	{
		cout << "a:" << a << "b: " << b << endl;
	}

protected:
private:
	int a;
	int b;
};
void test()
{
	Test t1; //調用無參構造函數
	cout << "hello..." << endl;
}

#endif 

第2種情況

#if 1
class Test
{
	//第2種情況  編譯通過
		Test()
		{
			printf("默認的構造函數\n");
		}
	void printT()
	{
		cout << "a:" << a << "b: " << b << endl;
	}

protected:
private:
	int a;
	int b;
};
void test()
{
	Test t1; //調用無參構造函數
	cout << "hello..." << endl;
}

#endif 

第3種情況

#if 1
class Test
{
public:
		//第3種情況  編譯不通過
	Test(int _a, int _b)//會
	{
		;
	}
void printT()
	{
		cout << "a:" << a << "b: " << b << endl;
	}

protected:
private:
	int a;
	int b;
};
void test()
{
	Test t1; //調用無參構造函數
	cout << "hello..." << endl;
}

#endif 

結果:
在這裏插入圖片描述

第4種情況
當類中定義了拷貝構造函數時,c++編譯器不會提供無參數構造函數


#if 1
class Test
{
public:
	//第4種情況  編譯不通過
	Test(const Test& obj) //copy構造函數 作用: 用一個對象初始化另外一個對象
	{
		a = obj.a + 100;
		b = obj.b + 100;
	}
void printT()
	{
		cout << "a:" << a << "b: " << b << endl;
	}

protected:
private:
	int a;
	int b;
};
void test()
{
	Test t1; //調用無參構造函數
	cout << "hello..." << endl;
}

#endif 

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章