运算符重载

(重定向自過載)
多态 |
---|
特设多态 |
參數多态 |
子类型 |
编程范型 |
---|
在计算机程序设计中,运算符重载(英語: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;
}
分类[编辑]
支持运算符重载和定义新运算符的语言:
支持运算符重载的语言:
不支持运算符重载的语言:
注释与引用[编辑]
- ^ Stroustrup, Bjarne. Operator Overloading. C++ FAQ. [27 August 2020]. (原始内容存档于14 August 2011).
- ^ Methods. Official Ruby FAQ. [2022-04-29]. (原始内容存档于2022-06-28).
- ^ Type classes instead of overloading.
- ^ 6.6 Overloading of Operators. Annotated Ada Reference Manual. [2022-04-29]. (原始内容存档于2018-07-19).
- ^ C++ Operator Overloading. [2022-04-29]. (原始内容存档于2019-02-26).
- ^ 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).
- ^ Operator Overloading - D Programming Language. dlang.org. [2020-10-10]. (原始内容存档于2022-05-30).
- ^ Operator overloading. Kotlin. [24 June 2018]. (原始内容存档于2022-05-24).
- ^ 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).
- ^ 3. Data Model. The Python Language Reference. [2022-04-29]. (原始内容存档于2012-10-26).
- ^ Binary functions with a symbolic name can be called infix.
- ^ Introduction. freepascal.org. [2020-09-30]. (原始内容存档于2020-08-11).
- ^ Operator Overloading. bourabai.kz. [2021-04-07]. (原始内容存档于2020-02-22).
- ^ How to: Define an Operator (Visual Basic). [2022-04-29]. (原始内容存档于2022-04-29).
- ^ Operator Overloading. Delphi Manual. [1 December 2014]. (原始内容存档于2019-04-15).
- ^ Metamethods Tutorial. Lua-users Wiki. [2022-04-29]. (原始内容存档于2022-05-06).
- ^ 字符串使用“+”运算符串联一般不认为是运算符重载,而是编译器“魔法”,即将相应操作转译为StringBuilder类的调用。
|