賦值運算符重載與拷貝構造函數
(1)區分初始化時的賦值(一般就叫初始化),和非初始化時的賦值(一般就叫賦值)
(2)實驗驗證初始化和賦值時各自對應
避免賦值運算符中的自賦值
(1)自賦值就是Person a; a = a;
(2)自賦值如果不處理,輕則浪費效率,重則導致內存丟失(該深拷貝時做了淺拷貝,在2.4.8中詳解)
(3)避免自賦值很簡單,只需要在賦值運算符重載函數所有操作前加上一個判斷 if (this != &other)即可
// 重載賦值運算符// Coordinate operator=(const Coordinate &other)// {//這樣會導致重載賦值運算時會執行這個函數Coordinate &operator=(const Coordinate &other) { //這樣就不會std::cout << " 重載賦值運算符 " << std::endl;if (this == &other) {return *this; // 處理自賦值}x = other.x;y = other.y;return *this;}
賦值運算符重載函數返回引用
返回引用好處1:提升程序效率
(1)賦值運算符重載函數返回值可以返回對象類型,也可以返回對象引用類型,都能工作。代碼驗證
(2)區別在于:返回引用可以避免一次返回值值傳遞的對象復制,這需要消耗資源的。代碼驗證
(3)總結:雖然C++語法并未強制要求,但是好的寫法是應該返回引用
返回引用好處2:允許連續賦值式
(1)返回對象而不是引用時,在連續賦值(c = a = b;)時會編譯可以,運行也可以,但是效率低同1中所講。
(2)原因是先執行a=b操作,返回值再作為第2次賦值運算的右值(也就是函數參數),對象和引用是類型兼容的
(3)總結:連等在返回對象和引用時都可以,但是在返回void時就不可以了
Coordinate &operator=(const Coordinate &other) { //這樣就不會std::cout << " 重載賦值運算符 " << std::endl;if (this == &other) {return *this; // 處理自賦值}x = other.x;y = other.y;return *this;}Coordinate *operator=(const Coordinate *other) {std::cout << " *other重載賦值運算符 " << std::endl;if (this == other) {return this; // 處理自賦值}x = other->x;y = other->y;return this;}Coordinate a(3, 4);Coordinate b = a; // 拷貝構造函數Coordinate c;c = &a; //*other重載賦值運算符 c = b; // 重載賦值運算符std::cout << "a: " << a << std::endl;std::cout << "b: " << b << std::endl;std::cout << "c: " << c << std::endl;
總結
定義新變量并且使用已有變量對堆新變量進行初始化時會調用拷貝構造函數
對已經定義的變量使用已有變量進行賦值運算時會調用賦值運算符
函數返回值不同,不能構成重載
運算符重載傳參的尷尬,導致引用的產生
學習記錄,侵權聯系刪除。
來源:朱老師物聯網大課堂