C++ 快速導覽 - 類別 重載運算子

運算子 (operator) 可依類別 (class) 的需要進行重載 (overload) ,舉例如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
 
class Demo {
public:
    Demo() {
        a = 1;
        b = 1;
    }
 
    Demo(int pa, int pb) {
        a = pa;
        b = pb;
    }
     
    Demo operator+(const Demo& p) {
        Demo demo;
        demo.a = this->a + p.a;
        demo.b = this->b + p.b;
        return demo;
    }            
 
    void do_something() {
        std::cout << a + b << std::endl;
    }
 
private:
    int a;
    int b;
     
};
 
int main(void) {
    Demo d1(2, 6);
    d1.do_something();
    Demo d2(10, 24);
    d2.do_something();
    Demo d3;
    d3 = d1 + d2;
    d3.do_something();
 
    return 0;
}
 
/* 《程式語言教學誌》的範例程式
    檔名:classdemo18.cpp
    功能:示範 C++ 程式
    作者:張凱慶
    時間:西元 2013 年 1 月 */


運算子重載在第 15 行, operator 後面接上要重載的運算子,另外要有 const 的參考 (reference) 參數 (parameter) ,表示運算子後面的運算元 (operand)
11
12
13
14
15
16
Demo operator+(const Demo& p) {
    Demo demo;
    demo.a = this->a + p.a;
    demo.b = this->b + p.b;
    return demo;
}


編譯執行結果如下



中英文術語對照
運算子operator
類別class
重載overload
參考reference
參數parameter
運算元operand


您可以繼續參考
類別


相關目錄
回 C++ 快速導覽
回 C++ 教材
回首頁


參考資料
C++ reference
cplusplus.com
Cprogramming.com C++ Tutorial

C++ Primer, Fourth Edition, Stanley B. Lippman...