運算子多載

本頁使用了標題或全文手工轉換
維基百科,自由的百科全書

在電腦程式設計中,運算子多載(英語:operator overloading)是多型的一種。這裏,運算子(比如+===)被當作多型函數,它們的行為隨着其參數類型的不同而不同。運算子並不一定總是符號。

簡介[編輯]

運算子多載通常只是一種語法糖[1]。它可以簡單地通過函數呼叫來模擬:

a + b * c

在一個支援運算子多載的語言裏,上面的寫法要比下面的寫法有效而簡練:

add(a, multiply(b, c))

(假設運算子* 的優先級高於運算子 +)

當一種語言允許運算子在某種情況下被隱式呼叫的時候,運算子多載將不只提供寫法上的方便。例如,Ruby中的to_s運算子就是如此,它將一個對象轉換為字串。

用途[編輯]

運算子多載由於使程式設計師能夠根據運算子類型的不同來決定運算子功能的不同而有多樣用途。C++<<的使用就是一個例子。表達式

a << 1

a是整型變數時將返回a的兩倍,但是當a是一個輸出流時將向這個流中寫入「1」。因為運算子多載允許程式設計師改變運算子通常的語意,慎重使用運算子多載通常被認為是一個好習慣。

簡易實例[編輯]

以下是C++語言範例:

#include <iostream>
using namespace std;
class point {
public:
	int x, y;
	point() {
		x = y = 0;
	}
	point(int ix, int iy) {
		x = ix;
		y = iy;
	}
	point pointxyadd(point pi) {
		return point(x + pi.x, y + pi.y);
	}
	point operator+(point pi) {
		return point(x + pi.x, y + pi.y);
	}
};
int main() {
	point p1(5, 10), p2(8, 13), p3, p4;
	p3 = p1.pointxyadd(p2);
	p4 = p1 + p2;
	cout << "p3 = (" << p3.x << ',' << p3.y << ')' << endl;
	cout << "p4 = (" << p4.x << ',' << p4.y << ')' << endl;
	return 0;
}

分類[編輯]

支援運算子多載和定義新運算子的語言:

支援運算子多載的語言:

不支援運算子多載的語言:

註釋與參照[編輯]

  1. ^ Stroustrup, Bjarne. Operator Overloading. C++ FAQ. [27 August 2020]. (原始內容存檔於14 August 2011). 
  2. ^ Methods. Official Ruby FAQ. [2022-04-29]. (原始內容存檔於2022-06-28). 
  3. ^ Type classes instead of overloading.
  4. ^ 6.6 Overloading of Operators. Annotated Ada Reference Manual. [2022-04-29]. (原始內容存檔於2018-07-19). 
  5. ^ C++ Operator Overloading. [2022-04-29]. (原始內容存檔於2019-02-26). 
  6. ^ Drayton, Peter; Albahari, Ben; Neward, Ted. C# in a Nutshell. O'Reilly Media, Inc. 2003 [2022-04-29]. ISBN 978-0-596-00526-9. (原始內容存檔於2022-04-29). 
  7. ^ Operator Overloading - D Programming Language. dlang.org. [2020-10-10]. (原始內容存檔於2022-05-30). 
  8. ^ Operator overloading. Kotlin. [24 June 2018]. (原始內容存檔於2022-05-24). 
  9. ^ Orwant, Jon. Computer Science & Perl Programming: Best of The Perl Journal. O'Reilly Media, Inc. 4 November 2002: 347– [2022-04-29]. ISBN 978-0-596-00310-4. (原始內容存檔於2022-05-14). 
  10. ^ 3. Data Model. The Python Language Reference. [2022-04-29]. (原始內容存檔於2012-10-26). 
  11. ^ Binary functions with a symbolic name can be called infix.
  12. ^ Introduction. freepascal.org. [2020-09-30]. (原始內容存檔於2020-08-11). 
  13. ^ Operator Overloading. bourabai.kz. [2021-04-07]. (原始內容存檔於2020-02-22). 
  14. ^ How to: Define an Operator (Visual Basic). [2022-04-29]. (原始內容存檔於2022-04-29). 
  15. ^ Operator Overloading. Delphi Manual. [1 December 2014]. (原始內容存檔於2019-04-15). 
  16. ^ Metamethods Tutorial. Lua-users Wiki. [2022-04-29]. (原始內容存檔於2022-05-06). 
  17. ^ 字串使用「+」運算子串聯一般不認為是運算子多載,而是編譯器「魔法」,即將相應操作轉譯為StringBuilder類的呼叫。