Copy constructor vs assignment operator in C++
阿新 • • 發佈:2021-01-13
從現有物件建立新物件時,是Copy Constructor。 當已初始化的物件從另一個現有物件中分配了新值時,是Assignment Operator。當然,看到這句話,你還是不懂.下面看一下程式碼
#include<iostream> #include<stdio.h> using namespace std; class Test { public: Test() {} Test(const Test &t) { cout<<"Copy constructor called "<<endl; } Test& operator = (const Test &t) { cout<<"Assignment operator called "<<endl; return *this; } }; // Driver code int main() { Test t1, t2; t2 = t1; //這裡是Assignmeng operator Test t3 = t1; //這裡是copy constrctor getchar(); return 0; }
看到程式碼是不是清楚了些,不過你記得小時候這樣的程式碼
#include<iostream> #include<stdio.h> using namespace std; class Test { public: Test() {} int a = 0; }; // Driver code int main() { Test t1, t2; t1.a = 3; t2 = t1; cout << t2.a << endl; //輸出3 Test t3 = t1; cout << t3.a << endl; //輸出3 getchar(); return 0; }
你沒有寫copy construct 怎麼也會賦值上,這是因為編譯器偷偷的給你把copy construct和assignment operator寫上去了. 可以這樣搞一下
#include<iostream> #include<stdio.h> using namespace std; class Test { public: Test() {} int a = 0; Test(const Test &t) = delete; Test& operator = (const Test &t) = delete; }; // Driver code int main() { Test t1, t2; t1.a = 3; t2 = t1; //編譯錯誤 cout << t2.a << endl; Test t3 = t1; //編譯錯誤 cout << t3.a << endl; getchar(); return 0; }
這樣,就相當於你警告編譯器不要多事.