在 C++ 中,我們什麼時候需要編寫自己的賦值運算子?


這裡我們將瞭解在 C++ 中何時需要建立自己的賦值運算子。如果一個類沒有任何指標,那麼我們不需要建立賦值運算子和複製建構函式。C++ 編譯器為每個類建立複製建構函式和賦值運算子。如果這些運算子不夠用,那麼我們就必須建立自己的賦值運算子。

示例

 即時演示

#include<iostream>
using namespace std;
class MyClass { //no user defined assignment operator or copy constructor is present
   int *ptr;
   public:
      MyClass (int x = 0) {
         ptr = new int(x);
      }
   void setValue (int x) {
      *ptr = x;
   }
   void print() {
      cout << *ptr << endl;
   }
};
main() {
   MyClass ob1(50);
   MyClass ob2;
   ob2 = ob1;
   ob1.setValue(100);
   ob2.print();
}

輸出

100

在 main() 函式中,我們使用 setValue() 方法為 ob1 設定了 x 的值。該值也反映在物件 ob2 中;這種意外的變化可能會產生一些問題。沒有使用者定義的賦值運算子,因此編譯器會建立一個。這裡它將 RHS 的 ptr 複製到 LHS。因此,這兩個指標都指向同一個位置。

為了解決這個問題,我們可以採用兩種方法。我們可以建立一個虛擬的私有賦值運算子來限制物件的複製,或者建立我們自己的賦值運算子。

示例

 即時演示

#include<iostream>
using namespace std;
class MyClass { //no user defined assignment operator or copy constructor is present
   int *ptr;
   public:
      MyClass (int x = 0) {
         ptr = new int(x);
      }
   void setValue (int x) {
      *ptr = x;
   }
   void print() {
      cout << *ptr << endl;
   }
   MyClass &operator=(const MyClass &ob2) {
      // Check for self assignment
      if(this != &ob2)
         *ptr = *(ob2.ptr);
      return *this;
   }
};
main() {
   MyClass ob1(50);
   MyClass ob2;
   ob2 = ob1;
   ob1.setValue(100);
   ob2.print();
}

輸出

50

這裡賦值運算子用於建立深複製並存儲單獨的指標。有一點我們必須牢記。我們必須檢查自引用,否則賦值運算子可能會更改當前物件的值。

更新於: 2019-07-30

369 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.