首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 操作符重載概述

     編輯:關於C++

什麼是操作符重載

操作符重載 = 操作符 + 重載。C++ 允許為自定義類型賦予運算符新含義,體現多態特性。

class Point {
public:
    int x, y;
    Point(int _x, int _y) : x(_x), y(_y) {}
    Point operator+(Point &p) {
        return Point(this->x + p.x, this->y + p.y);
    }
};

int main() {
    Point p1(1,3), p2(2,6);
    Point p3 = p1 + p2; // 調用 p1.operator+(p2)
    cout << "p3:(" << p3.x << "," << p3.y << ")"; // 輸出 (3,9)
}

實現方式

兩種方式:類成員函數 和 友元函數。

class Point {
public:
    int x, y;
    Point(int _x, int _y);
    Point operator+(Point &p);        // 成員函數,隱含 this 指針
    friend int operator*(Point &p1, Point &p2); // 友元函數,需兩個參數
};

成員函數參數比運算元少一個(靠 this),友元函數需顯式提供所有操作數。

完整示例

#include <iostream>
using namespace std;

class Point {
public:
    int x, y;
    Point(int _x, int _y) : x(_x), y(_y) {}
    Point operator+(Point &p) { // 向量加
        return Point(this->x + p.x, this->y + p.y);
    }
    friend int operator*(Point &p1, Point &p2); // 內積
};

int operator*(Point &p1, Point &p2) {
    return p1.x * p2.x + p1.y * p2.y;
}

int main() {
    Point p1(1,3), p2(2,6);
    cout << p1 * p2 << endl;       // 20
    Point p3 = p1 + p2;
    cout << "p3:(" << p3.x << "," << p3.y << ")" << endl; // (3,9)
}

注意事項

  1. 重載運算符必須至少有一個類類型參數,不能重載內置類型運算符。
  2. 運算符優先級和結合性不可改變。
  3. 失去短路求值特性(如 &&, || 會求值所有操作數)。
  4. 不應重載已有內置含義的運算符(如賦值、取址、逗號)。
  5. 只能重載現有 C++ 運算符,不能創建新運算符。
  6. 不可重載:.、::、sizeof、?:。
  7. 運算元個數不可改變。

前置/後置 ++、-- 重載特例

前置返回引用,後置返回值並接受 int 佔位參數區分:

class Counter {
    int val;
public:
    Counter& operator++() { ++val; return *this; }       // 前置 ++c
    Counter operator++(int) { Counter t=*this; ++val; return t; } // 後置 c++
};
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved