重载的运算符即为函数;
运算符重载的原因:运算符对操作数类型不支持。
将运算符移植到新的类型上。
运算符作为函数,与普通函数的调用形式有所不同。
函数:函数名(参量);
运算符:按照运算符的写法。
aa @ bb; // 隐式调用
aa.operator @(bb); // 显式调用
c++
class ca { public: int value; //重载为成员函数格式 int operator+(const ca &v){ return this->value + v.value; // 等同于return value+v.value; } }; //重载为非成员函数格式 int operator+(const ca &v1, const ca &v2) { return v1.value + v2.value; } int main() { ca a, b; a.value = 10; b.value = 20; printf("a+b:%d ", a + b); // 优先用成员函数 return 0; }
swift:
infix operator <-- : LogicalConjunctionPrecedence
public func <-- <T>(property: inout T, name: String) -> CustomMappingKeyValueTuple {
return property <-- [name]
}