共用方式為


指派

指派運算符 (=) 是二元運算子,嚴格來說就是二元運算符。 它的宣告與任何其他二元運算子相同,但有下列例外狀況:

  • 它必須為非靜態成員函式。 No operator= 可以宣告為非member 函式。
  • 衍生類別不會進行繼承。
  • 如果不存在,則編譯程式可以針對類別類型產生預設 operator= 函式。

下列範例說明如何宣告指派運算子:

class Point
{
public:
    int _x, _y;

    // Right side of copy assignment is the argument.
    Point& operator=(const Point&);
};

// Define copy assignment operator.
Point& Point::operator=(const Point& otherPoint)
{
    _x = otherPoint._x;
    _y = otherPoint._y;

    // Assignment operator returns left side of assignment.
    return *this;
}

int main()
{
    Point pt1, pt2;
    pt1 = pt2;
}

提供的自變數是表達式的右側。 運算子會傳回物件以保留指派運算子的行為,而該運算子會在指派完成後傳回左方的值。 這允許鏈結指派,例如:

pt1 = pt2 = pt3;

複製指派運算子不會與複製建構函式混淆。 後者會在從現有的 物件建構期間呼叫:

// Copy constructor is called--not overloaded copy assignment operator!
Point pt3 = pt1;

// The previous initialization is similar to the following:
Point pt4(pt1); // Copy constructor call.

注意

建議遵循 個規則,定義複製指派運算符的類別也應該明確定義複製建構函式、解構函式,以及從 C++11 開始,移動建構函式和移動指派運算符。

另請參閱