操作符的重载可以扩展操作符的功能,操作符的重载以特殊形式的函数的方式进行
定义:
通过operator操作符可以定义特殊的函数。(本质是通过函数重载操作符)
Type operator sign(const Type p1,const Type p2) //sign是操作符(+,-,*,/) { Type ret; return ret; }
例(扩展+符号的功能):
#include <stdio.h> class Complex { int a; int b; public: Complex(int a = 0, int b = 0) { this->a = a; this->b = b; } int getA() { return a; } int getB() { return b; } friend Complex operator + (const Complex& p1, const Complex& p2); // 定义类的友元函数 }; Complex operator + (const Complex& p1, const Complex& p2) // 操作符 + 重载的定义。已经用函数扩展了操作符的功能 { Complex ret; ret.a = p1.a + p2.a; ret.b = p1.b + p2.b; return ret; } int main() { Complex c1(1, 2); Complex c2(3, 4); Complex c3 = c1 + c2; // 两种写法都行,直接调用operator + 函数。 //Complex c3 = operator + (c1, c2) printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB()); return 0; }