以友元函数的方式重载
class Complex
{
private:
double real, imag;
public:
Complex() = default;
Complex(double r, double i);
~Complex() = default;
/* 赋值运算符只能以成员函数的形式重载 */
Complex& operator=(const Complex &p);
friend Complex operator+(const Complex &p1, const Complex &p2);
friend Complex operator-(const Complex &p1, const Complex &p2);
friend Complex operator*(const Complex &p1, const Complex &p2);
friend Complex operator/(const Complex &p1, const Complex &p2);
friend Complex operator++(Complex &p, int); // 后置++重载
friend Complex operator--(Complex &p, int); // 后置--重载
friend Complex &operator++(Complex &p); // 前置++重载
friend Complex &operator--(Complex &p); // 前置--重载
friend bool operator>(const Complex& p1, const Complex& p2);
friend bool operator<(const Complex& p1, const Complex& p2);
friend bool operator>=(const Complex& p1, const Complex& p2);
friend bool operator<=(const Complex& p1, const Complex& p2);
friend bool operator==(const Complex& p1, const Complex& p2);
friend bool operator!=(const Complex& p1, const Complex& p2);
/* 输入输出运算符最好是以友元的方式重载 */
friend ostream &operator<<(ostream &o, const Complex &p);
friend istream &operator>>(istream &i, Complex& p);
};
以成员函数的方式重载
class Complex
{
private:
double real, imag;
public:
Complex() = default;
Complex(double r, double i);
~Complex() = default;
/* 赋值运算符只能以成员函数的形式重载 */
Complex& operator=(const Complex &p);
Complex operator+(const Complex &p);
Complex operator-(const Complex &p);
Complex operator*(const Complex &p);
Complex operator/(const Complex &p);
Complex operator++(int); // 后置++重载
Complex operator--(int); // 后置--重载
Complex &operator++(); // 前置++重载
Complex &operator--(); // 前置--重载
bool operator>(const Complex& p);
bool operator<(const Complex& p);
bool operator>=(const Complex& p);
bool operator<=(const Complex& p);
bool operator==(const Complex& p);
bool operator!=(const Complex& p);
ostream &operator<<(ostream &o);
istream &operator>>(istream &i);
};
若以成员函数的方式重载输入输出运算符则在使用时会别捏,因为重载的函数中第一个参数是
this指针,所以在使用运算符时,第一个传入的参数应该是类类型,第二个参数才是流类型。
int main(int argc, char const *argv[])
{
Complex p1;
/*
输入输出运算符最好是用友元的方式重载,不然用起来很别扭
不符合正常的用法
*/
/* 成员函数方式重载 */
p1 >> cin;
p1 << cout << endl;
/* 友元函数方式重载 */
// cin >> p1;
// cout << p1 << endl;
return 0;
}