什麼時候應該在 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

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

更新於: 18-Dec-2019

173 次瀏覽

開啟你的 事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.