什么是操作符重载
C++ 里面操作符就是一种函数,而用户可以重定义或重载 C++ 内置的运算符。例如,实现两个复数相加的功能需要实部、虚部分别相加。
//语法:
返回值类型 operator op (参数);
//示例:
returnType operator+=(const type& a, const type& b);
方式一:成员函数的方式重载
编译器中,所有的成员函数都带有一个隐藏的参数 this
,谁调用该函数,谁就是 this
。
在执行c2 += c1
时,操作符 += 作用于 c2,而 c1 是参数。
class complex
{
public:
complex(double r=0, double i=0): re(r), im(i){}
//返回引用是因为,可能存在(c3 += c2 += c1;)的用法
complex& complex::operator+= (const complex& r)
{
//this指的是调用+=的对象,即c2,即 c2->re += r.re
this->re += r.re;
this->im += r.im;
return *this;
}
double real() const {return re;}
double imag() const {return im;}
private:
double re, im;
}
//创建对象,将复数c1与c2相加的结果保存在c2中
{
complex c1(2, 1);
complex c2(5, 6);
c2 += c1;
}
方式二:全局函数的方式重载
例子:操作符 <<
,并且 <<
只能以全局函数的形式重载。
cout
是 ostream
对象。
#include <iostream.h>
//第一个参数os不能加 const(★★★★★)
ostream& operator<<(ostream& os, const complex& x)
{
return os << '(' << x.real() << ',' << x.imag() << ')';
}
{
complex c1(2, 1);
complex c2(5, 6);
cout << c1 << c2; //结果:(2,1)(5,6)
}