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

C++ 運算子多載與函式多載:語法、範例與可不可載對照表

     編輯:C++ 入門

C++ 運算子多載與函式多載

C++ 允許同一作用域內對函式與運算子指定多重定義,分別稱為函式多載與運算子多載。編譯器根據引數型別進行多載決議選擇最合適版本。

函式多載

同名函式參數個數、型別、順序至少一項不同(不可僅靠回傳型別區分)。

class printData {
public:
    void print(int i) { cout << "int: " << i << endl; }
    void print(double f) { cout << "float: " << f << endl; }
    void print(char* c) { cout << "char: " << c << endl; }
};
// 呼叫:pd.print(5); pd.print(500.263); pd.print("Hello");

運算子多載

重新定義內建運算子行為,函式名稱格式:operator<符號>。可定義為成員函式或非成員函式。

成員函式形式(左運算元為 this)

class Box {
public:
    Box operator+(const Box& b) {
        Box box;
        box.length = this->length + b.length;
        box.breadth = this->breadth + b.breadth;
        box.height = this->height + b.height;
        return box;
    }
};
Box3 = Box1 + Box2;  // 呼叫 Box1.operator+(Box2)

非成員函式形式(需兩個參數)

Box operator+(const Box& a, const Box& b) { ... }

完整範例:Box 類別與 + 運算子多載

#include <iostream>
using namespace std;

class Box {
public:
    double getVolume() { return length * breadth * height; }
    void setLength(double l) { length = l; }
    void setBreadth(double b) { breadth = b; }
    void setHeight(double h) { height = h; }
    Box operator+(const Box& b) {  // 成員函式多載 +
        Box box;
        box.length = this->length + b.length;
        box.breadth = this->breadth + b.breadth;
        box.height = this->height + b.height;
        return box;
    }
private:
    double length, breadth, height;
};

int main() {
    Box Box1, Box2, Box3;
    Box1.setLength(6); Box1.setBreadth(7); Box1.setHeight(5);
    Box2.setLength(12); Box2.setBreadth(13); Box2.setHeight(10);
    cout << "Box1: " << Box1.getVolume() << endl;  // 210
    cout << "Box2: " << Box2.getVolume() << endl;  // 1560
    Box3 = Box1 + Box2;
    cout << "Box3: " << Box3.getVolume() << endl;  // 5400
    return 0;
}

可多載 / 不可多載運算子對照表

可多載不可多載
+ - * / % ^ & | ~ ! , = < > <= >= ++ -- << >> == != && || += -= *= %= ^= &= |= <<= >>= [] () -> ->* new new[] delete delete[] :: .* . ?:

常見運算子多載分類

  1. 一元運算子(++ -- + - ! ~)
  2. 二元運算子(+ - * / % = < > == !=)
  3. 關係運算子(== != < > <= >=)
  4. 輸入/輸出運算子(<< >>)
  5. ++ -- 前綴/後綴區分
  6. 指派運算子(= += -=)
  7. 函式呼叫運算子 ()
  8. 下標運算子 []
  9. 類別成員存取運算子 ->
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved