1. 程式人生 > >例項解釋在過載賦值符時複製建構函式和無參建構函式的呼叫

例項解釋在過載賦值符時複製建構函式和無參建構函式的呼叫

#include<iostream>
#include<string>
//#define VNAME(x) #x;
using namespace std;
class Number {
public:
	int num;
	std::string name;
	Number(std::string _name = "nonPara", int n = 0) : num(n), name(_name){
		std::cout << "啟動無參建構函式:" << name << std::endl;
	}
	// 在此處補充你的程式碼
	//Number& operator*(Number that){//如果返回Number&,必須用new, 不然Number(xxx,xxx)是在函式體構造的,一旦函式
	//	//結束就釋放,等到賦值符運算時,傳入的number& that是空便會出錯
	//	return *(new Number("*creature", (this->num)*(that.num)));
	//}
	Number operator*(Number that){//因為返回Number,其實在乘法的呼叫過程會有:
		//1.Number that 對傳入引數其實進行了複製構造
		//2.Return 構造了Number creature
		//3.返回型別是Number不是Number&,因而會呼叫複製構造,把creature進行復制後返回,看到分隔符上還是呼叫了creature->copyconstruction
		//即使n1*n2左邊沒有等於號,也會呼叫複製構造。

		return Number("*creature", (this->num)*(that.num));
	}
	Number(Number& a){//複製建構函式!!!的引數列表不能有Number類的物件,應該是number的引用
		//否則這裡的傳入引數是必須呼叫複製構造的,但是確沒有在這之前定義複製構造
		num = a.num;
		name = "copyConstruction";
		std::cout << "啟動複製建構函式" << a.name << " -> " << this->name << std::endl;

	}
	Number& operator=(Number& that){//特別注意,過載賦值函式的時候類的成員函式情況
		//下應該是返回自己,因為作為成員的操作符函式,第一個傳入引數為(被省略)this指標
		std::cout << "呼叫賦值函式:" << this->num << that.name << " -> " << this->name << std::endl;
		//從這裡可以看到:其實過載賦值函式是先啟用無引數構造產生了this這個物件,然後再採用=
		this->num = that.num;
		return *this;
	}
	//friend int int(Number a); 
	operator int(){
		return num;
	}
};

int main() {
	Number n1("n1", 10), n2("n2", 20);
	n1*n2;
	std::cout << "我是分隔符-------------\n";
	Number n3("n3"); n3 = n1*n2;//n2會呼叫了複製構造
	cout << int(n3) << endl;
	system("pause");
	return 0;
}
//輸出結果
//啟動無參建構函式:n1
//啟動無參建構函式:n2
//啟動複製建構函式n2 -> copyConstruction               乘法傳入引數型別為Number,不是引用,因此呼叫複製構造
//啟動無參建構函式:*creature                           乘法的return 構造,構造體只存在在函式體內
//啟動複製建構函式*creature -> copyConstruction        返回型別為Number,需要複製出來
//我是分隔符-------------
//啟動無參建構函式:n3
//啟動複製建構函式n2 -> copyConstruction
//啟動無參建構函式:*creature
//啟動複製建構函式*creature -> copyConstruction
//呼叫賦值函式:0copyConstruction -> n3
//200