运算符重载
程序员文章站
2022-05-18 16:34:08
...
注意:重载用到ostream时,不能将ostream对象设为const常量,因为此类的成员需要对其他ostream类的方法进行操作。
重载加号:
Complex operator+(const Complex& A, const Complex& B) {
Complex c;
c.m_x = B.m_x + A.m_x;
c.m_y = B.m_y + A.m_y;
return c;
}
<<
ostream& operator<<( ostream& out, const Complex& A) {//重载<<运算符
out <<"[" <<A.m_x << ","<<A.m_y<<"]";
return out;
}
前置++和后置++
Complex Complex::operator++() {//前置
this->m_x++;
this->m_y++;
return *this;
}
~~Complex Complex::operator++(int x) {//错误的后置
Complex tmp = *this;
tmp.m_x++; //此处应该是this->m_x++; this->m_y++;
tmp.m_y++;
return tmp;
}~~
```cpp
Complex Complex::operator++(int x) {//正确的后置
Complex tmp = *this;
m_x++;
m_y++;
return tmp;
}
重载+=
```cpp
Complex Complex::operator+=(const Complex& c) {
this->m_x += c.m_x;
this->m_y += c.m_y;
return *this;
}
测试代码:
#include<iostream>
using namespace std;
#include"Complex.h"
int main() {
Complex c1(10), c2(20, 10);
cout << c1 << "+" << c2 << "=" << c1 + c2 << endl;
cout << (c1 += c2) << endl;
cout << c1++ << endl;
cout << ++c1 << endl;
return 0;
return 0;
}
错误的运行:
正确的运行结果为:
当我使用错误的重载时,用int型变量进行自增时也会错误。如下: