运算符重载
运算符重载的函数形式
operator op(argument); op是有效的运算符
#include<iostream>
using std::cout;
using std::cin;
using std::endl;
class Complex{
public:
float real;
float imag;
Complex(float real=0, float imag = 0);
Complex operator +(Complex & other) const; // const成员函数表示不会修改对象内容
void show() const;
};
Complex::Complex(float real, float imag)
{
this->real = real;
this->imag = imag;
}
Complex Complex::operator+(Complex & other) const
{
Complex comp;
comp.real = this->real + other.real;
comp.imag = this->imag + other.imag;
return comp;
}
void Complex::show() const
{
cout<<this->real<<" + "<<this->imag<<"j"<<endl;
}
int main()
{
Complex a = Complex(1,2);
Complex b = Complex(2,3);
Complex c = a+b;
c.show();
return 0;
}
运算符重载的限制
- 重载运算符函数不必是成员函数,但必须至少有一个操作数是用户定义的类型。这是为了防止对标准类型的运算产生影响。
- 使用运算符时不能违反运算符原来的句法规则。例如不能将求模运算符%重载成使用一个操作数。也不能修改运算符优先级。
- 不能创建新的运算符
- 不能重载:
- sizeof
- . 成员运算
- ::
- ? :
- typeid
- const_cast
- dynamic_cast
- reinterpret_cast
- static_cast
- 只能是成员函数
- =
-() - []
- ->
- =