C++ 重載運算符和重載函數
C++允許在同一作用域中的某個函數和運算符指定多個定義,分別稱為函數重載和運算符重載 。
重載聲明是指一個與之前已經在該作用域內聲明過的函數或方法具有相同名稱的聲明,但是它們的參數列表和定義(實現)不相同。
當您調用一個重載函數或重載運算符時,編譯器通過把您所使用的參數類型與定義中的參數類型進行比較,決定選用最合適的定義。 選擇最合適的重載函數或重載運算符的過程,稱為重載決策 。
C++ 中的函數重載
在同一個作用域內,可以聲明幾個功能類似的同名函數,但是這些同名函數的形式參數(指參數的個數、類型或者順序)必須不同。 您不能僅通過返回類型的不同來重載函數。
下面的實例中,同名函數print()被用於輸出不同的數據類型:
#include <iostream> using namespace std; class printData { public: void print(int i) { cout << "Printing int: " << i << endl; } void print(double f) { cout << "Printing float: " << f << endl; } void print(char* c) { cout << "Printing character: " << c << endl; } }; int main(void) { printData pd; // Call print to print integer pd.print(5); // Call print to print float pd.print(500.263); // Call print to print character pd.print("Hello C++"); return 0; }
當上面的代碼被編譯和執行時,它會產生下列結果:
Printing int: 5 Printing float: 500.263 Printing character: Hello C++
C++ 中的運算符重載
您可以重定義或重載大部分C++ 內置的運算符。 這樣,您就能使用自定義類型的運算符。
重載的運算符是帶有特殊名稱的函數,函數名是由關鍵字operator 和其後要重載的運算符符號構成的。 與其他函數一樣,重載運算符有一個返回類型和一個參數列表。
Box operator+(const Box&);
聲明加法運算符用於把兩個Box 對象相加,返回最終的Box 對象。 大多數的重載運算符可被定義為普通的非成員函數或者被定義為類成員函數。 如果我們定義上面的函數為類的非成員函數,那麼我們需要為每次操作傳遞兩個參數,如下所示:
Box operator+(const Box&, const Box&);
下面的實例使用成員函數演示了運算符重載的概念。 在這裡,對像作為參數進行傳遞,對象的屬性使用this運算符進行訪問,如下所示:
#include <iostream> using namespace std; class Box { public: double getVolume(void) { return length * breadth * height; } void setLength( double len ) { length = len; } void setBreadth( double bre ) { breadth = bre; } void setHeight( double hei ) { height = hei; } // 重载 + 运算符,用于把两个 Box 对象相加 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; // 长度 double breadth; // 宽度 double height; // 高度 }; // 程序的主函数 int main( ) { Box Box1; // 声明 Box1,类型为 Box Box Box2; // 声明 Box2,类型为 Box Box Box3; // 声明 Box3,类型为 Box double volume = 0.0; // 把体积存储在该变量中 // Box1 详述 Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // Box2 详述 Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // Box1 的体积 volume = Box1.getVolume(); cout << "Volume of Box1 : " << volume <<endl; // Box2 的体积 volume = Box2.getVolume(); cout << "Volume of Box2 : " << volume <<endl; // 把两个对象相加,得到 Box3 Box3 = Box1 + Box2; // Box3 的体积 volume = Box3.getVolume(); cout << "Volume of Box3 : " << volume <<endl; return 0; }
當上面的代碼被編譯和執行時,它會產生下列結果:
Volume of Box1 : 210 Volume of Box2 : 1560 Volume of Box3 : 5400
可重載運算符/不可重載運算符
下面是可重載的運算符列表:
+ | - | * | / | % | ^ |
& | | | ~ | ! | , | = |
< | > | <= | >= | ++ | -- |
<< | >> | == | != | && | || |
+= | -= | /= | %= | ^= | &= |
|= | *= | <<= | >>= | [] | () |
-> | ->* | new | new [] | delete | delete [] |
下面是不可重載的運算符列表:
:: | .* | . | ?: |
運算符重載實例
下面提供了各種運算符重載的實例,幫助您更好地理解重載的概念。
序号 | 运算符和实例 |
---|---|
1 | 一元运算符重载 |
2 | 二元运算符重载 |
3 | 关系运算符重载 |
4 | 输入/输出运算符重载 |
5 | ++ 和 -- 运算符重载 |
6 | 赋值运算符重载 |
7 | 函数调用运算符 () 重载 |
8 | 下标运算符 [] 重载 |
9 | 类成员访问运算符 -> 重载 |