1.运算符函数重载
#include <iostream>
using namespace std;
class ComplexNumber // 复数
{
float real; // 实部
float image;// 虚部
public:
// 无参构造函数、析构函数、赋值操作符函数、拷贝构造函数
ComplexNumber(float r=0, float i=0):real(r), image(i){}
// 对加法运算符+的重写
const ComplexNumber operator+(const ComplexNumber &r)
{
float rsum = this->real + r.real;
float isum = this->image + r.image;
return ComplexNumber(rsum, isum);
}
// 显示当前复数的值
void showValue()
{
cout << real << "+" << image << "i" << endl;
}
};
int main()
{
ComplexNumber a(1, 2), b(3, 4);
ComplexNumber c;
c = a+b; // 等价于 c = a.operator+(b);
c.showValue();
return 0;
}
2.前置、后置自增运算符、输出格式控制
- 为区别前置和后置运算符,需要在后置运算符函数中加参数“int”,虽然这个类型在此除了以示区别之外并不代表任何实际含义;
A & operator++(int) (后置)
A & operator++() (前置)
- c语言的语法规定:
int a, b;
a++ = b; // x = b; a=a+1; (错误的,编译不过)
++a = b; // a=a+1; a = b;
a++是先返回a值再+1,所以不可能返回a,那就只能先建立局部变量来保存a的初值,然后再返回局部变量(局部变量不允许返回引用),但返回了局部变量之后,如果再连着进行++运算,参与运算的就是这个局部变量的值了,所以此时a++=b其实等效与x++,系统是不允许这样的操作
- 为了遵循c语言的语法规则。C++也是不支持这样的操作。为了避免存在这种操作的可能(通过不正当的操作竟然也能让这样的操作编译通过),所以重载后置++运算符时要特别注意返回值类型
例如:
// 重载后置自增运算符
MyClock & operator++(int)
{
MyClock tmp = *this;
++(*this);
return tmp;
}
这是应当避免的。返回值类型为一个引用。在调用时可以c++=a编译通过,与我们的预期不符合。
正确做法:
// 重载后置自增运算符
const MyClock operator++(int)
{
MyClock tmp = *this;
++(*this);
return tmp;
}
返回值类型为const型就是为了避免后置运算符可以左值操作。