C++基礎知識學習,類的各種構造方法詳解,拷貝函數詳解

類相關的非成員函數

函數的聲明寫在類的聲明外部,在定義文件中去實現
testClass.h

class testClass
{

}
void printSomething(testClass& myClass);
#endif 

testClass.cpp

void printSomething(testClass& myClass)
{
	std::cout << "i am testClass" << std::endl;
}
類內初始化,類內的成員變量初始化

直接定義的時候就賦值,原則上是要用初始化列表的

class testClass
{
public:
	int a = 1;
	int b = 2;
	int c = 3;
public:
	testClass();
	testClass(int a,int b, int c);
};
testClass::testClass(int d, int e, int f) : a(d), b(e), c(f){}
const成員的初始化,如果不在定義的時候初始化,那麼所有的構造函數(拷貝函數)都要有給他賦值的語句
class testClass
{
public:
	int a = 1;
	int b = 2;
	int c = 3;
	//如果聲明的時候不進行初始化
	const int d;
public:
	testClass();
	testClass(int a,int b, int c);
};
testClass::testClass(int a) : d(1)
{
}
testClass::testClass(int d, int e, int f) : a(d), b(e), c(f), d(2)
{
}
默認構造函數,沒有參數的構造函數

沒有寫構造函數,類就會通過默認的無參的構造函數進行構造
因爲編譯器默認會定義一個默認的無參構造函數,成爲“合成的默認構造函數”
一旦我們寫了任何一個構造函數,編譯器就不會再爲我們合成任何構造函數

什麼情況下必須要寫構造函數?

成員變量中有其他的類,並且沒有無參的構造函數,所有的構造函數都要初始化這個類,參數列表也很簡單,寫着不麻煩

#ifndef __TESTCLASS__H__
#define __TESTCLASS__H__

class testClass2
{
public:
	testClass2(int a)
	{

	}
};

class testClass
{
public:
	int a;
	int b;
	int c;
public:
	//如果有另外一個類,所有的構造方法都要進行該屬性的初始化
	testClass2 testclass2;

	testClass();

	explicit testClass(int a);

	testClass(int d, int e, int f);
};
#endif 
testClass::testClass() :testclass2(2) {}
testClass::testClass(int a) :  testclass2(2){}
testClass::testClass(int d, int e, int f) : a(d), b(e), c(f)testclass2(2) {}
=default,=delete
  • =defalut,在聲明文件中,類的無參構造方法聲明後面加上 = default ,編譯器自動爲我們生成函數體
  • = delete,程序員顯示的禁用某個函數

拷貝構造函數

拷貝構造函數會把屬性挨個進行拷貝,但是如果自己定義了拷貝構造函數,那麼就會完全按照自己的定義來進行

testClass class1(1, 2, 3);
testClass class2 = class1;	//調用了拷貝構造函數
testClass class3(class1);	//調用了拷貝構造函數
testClass class4 = { class1 };	//調用了拷貝構造函數
testClass class5{ class1 };	//調用了拷貝構造函數
testClass class6;
class6 = class1;	//沒有調用開拷貝構造函數,之後會進行解釋

拷貝構造函數如果除了本身的引用之外,還要加入其他的參數的話,必須給默認值(在聲明文件中,定義文件不需要)

testClass(const testClass& myself, int d = 12);
testClass::testClass(const testClass& myself, int d) : testclass2(2)
{
	std::cout << "系統調用了拷貝構造函數" << std::endl;
}
  • 建議引用使用const
  • 建議不要加上explicit前綴
發生拷貝構造函數的其他情況
  • 1、將類傳遞給一個非引用的函數func(class1);
void func(testClass test)
{
}
  • 2、一個方法返回一個類的時候
testClass func(testClass test)
{
	testClass test2 = test1;
	//返回這個對象test2的時候,也是調用的拷貝函數,
	//然後再返回那個拷貝的對象
	return test2;
}
發佈了157 篇原創文章 · 獲贊 167 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章