C++ 运算符重载
1、运算符重载
- 对已有的运算符赋予多重的含义
- 使同一运算符作用于不同类型的数据时产生不同类型的行为
目的
- 扩展C++中提供的运算符的适用范围,以用于类所表示的抽象数据类型
运算符的重载实质是函数重载,类型如下:
返回值类型 operator 运算符(形参表) { ... }
在程序编译时
- 把含运算符的表达式 -> 对 运算符函数 的调用
- 把运算符的操作数作为运算符函数的参数
- 运算符被多次重载时,根据实参的类型决定调用哪个运算符函数
- 运算符可以被重载成普通函数,也可以被重载成类的成员函数
运算符重载为普通函数示例:
#include <iostream> using namespace std; class Complex { public: Complex(double r = 0.0, double i = 0.0) { real = r; img = i; } double real; // real part double img; // imaginary part }; Complex operator + (const Complex &a, const Complex &b) { return Complex(a.real+b.real, a.img+b.img); } int main() { Complex a(1, 2), b(2, 3), c; c = a + b; cout << c.real << ":" << c.img << endl; }
这里a+b 就相当于 operator+(a, b);
重载为普通函数时,参数个数为运算符数目。
运算符重载为成员函数示例:(重载为成员函数时,参数个数为运算符数目减一)
#include <iostream> using namespace std; class Complex { public: Complex(double r = 0.0, double i = 0.0) { real = r; img = i; } Complex operator+(const Complex &); // addition Complex operator-(const Complex &); // subtraction double real; // real part double img; // imaginary part }; Complex Complex::operator +(const Complex & operand2) { return Complex(real+operand2.real, img+operand2.img); } Complex Complex::operator -(const Complex & operand2) { return Complex(real-operand2.real, img-operand2.img); } int main() { Complex a(1, 2), b(2, 3), c; c = a + b; cout << c.real << ":" << c.img << endl; c = b - a; cout << c.real << ":" << c.img << endl; }