操作符的重载
操作符的重载可以扩展操作符的功能,操作符的重载以特殊形式的函数的方式进行
定义:
通过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; }
全局函数和类的成员函数都可以进行操作符的重载。
也可以将操作数重载函数定义为成员函数。
例:复数操作符的重载函数
#ifndef _COMPLEX_H_ #define _COMPLEX_H_ class Complex { double a; double b; public: Complex(double a = 0, double b = 0); double getA(); double getB(); double getModulus(); Complex operator + (const Complex& c); Complex operator - (const Complex& c); Complex operator * (const Complex& c); Complex operator / (const Complex& c); bool operator == (const Complex& c); bool operator != (const Complex& c); Complex& operator = (const Complex& c); }; #endif
操作符重载的注意事项:
1. 赋值操作符只能重载为成员函数。
2. 重载函数不应改变操作符的语义。