运算符重载:即为函数
生活随笔
收集整理的这篇文章主要介绍了
运算符重载:即为函数
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
重载的运算符即为函数;
运算符重载的原因:运算符对操作数类型不支持。
将运算符移植到新的类型上。
运算符作为函数,与普通函数的调用形式有所不同。
函数:函数名(参量);
运算符:按照运算符的写法。
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\n", a + b); // 优先用成员函数return 0; }
swift:
运算符重载的原因:运算符对操作数类型不支持。
将运算符移植到新的类型上。
运算符作为函数,与普通函数的调用形式有所不同。
函数:函数名(参量);
运算符:按照运算符的写法。
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\n", a + b); // 优先用成员函数return 0; }
swift:
infix operator <-- : LogicalConjunctionPrecedence
public func <-- <T>(property: inout T, name: String) -> CustomMappingKeyValueTuple {
return property <-- [name]
}
总结
以上是生活随笔为你收集整理的运算符重载:即为函数的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: Algs4-1.5.4给出id[]和sz
- 下一篇: 在Project 2010中添加自定义任