写复数加减法的时候看到的运算符的重载以及配合友元friend的使用
#include <iostream>
using namespace std;
/*
3.定义一个复数类
提供构造函数
提供成员方法 计算 复数的 加法 减法 乘法 除法
*/
class Complex
{
private:
double real;
double imag;
public:
Complex(){}
Complex(double real, double imag):real(real), imag(imag) {}
void show_num(void) const
{
if(real != 0)
cout << real;
if(imag != 0)
{
if(imag < 0)
cout << imag << "i";
else
cout << "+" << imag << "i";
}
cout << endl;
}
//重载运算符 两种写法
//第一种使用friend以全局(友元)方式重载 两个参数都作为操作数
//第二种不以全局(友元)方式重载 则只能用传一个参数 第一个操作数则是当前类的对象
/*friend Complex operator+(Complex& c1, Complex& c2)
{
Complex tmp;
tmp.real = c1.real + c2.real;
tmp.imag = c1.imag + c2.imag;
return tmp;
}*/
//加法:(a+bi)+(c+di)=(a+c)+(b+d)i
Complex operator+(const Complex& c) const
{
return Complex(real + c.real, imag + c.imag);
}
//减法:(a+bi)-(c+di)=(a-c)+(b-d)i
Complex operator-(const Complex& c) const
{
return Complex(real - c.real, imag - c.imag);
}
//乘法:(a+bi)*(c+di)=(ac-bd)+(ad+bc)i
Complex operator*(const Complex& c) const
{
return Complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real);
}
//声明全局函数为友元函数 << >>只能以全局函数方式重载
friend ostream& operator<<(ostream& os, const Complex& c)
{
os << c.real << "+" << c.imag << "i";
return os; //要有返回值
}
friend istream& operator>>(istream& is, Complex& c)
{
is >> c.real >> c.imag;
return is; //要有返回值
}
};
//重载前++后++
class Int
{
public:
Int(const int& n = 0):n(n){};
//前++返回左值 需要加引用
Int& operator++(void)
{
++n;
return *this;
}
//为了防止歧义,使用哑元 后++返回右值
Int operator++(int)
{
Int tmp(*this);
++n;
return tmp;
}
Int& operator--(void)
{
--n;
return *this;
}
Int operator--(int)
{
Int tmp(*this);
--n;
return tmp;
}
friend ostream& operator<<(ostream& os, const Int a)
{
os << a.n;
return os;
}
private:
int n;
};
int main(int argc, char *argv[])
{
Complex num1(1, 2);
Complex num2(2, 3);
Complex num3(3, 3);
cin >> num3;
cout << num3 << endl;
cout << "------------" << endl;
Int a1(1024);
Int a2 = a1++;
cout << a2 << endl;
cout << a1 << endl;
cout << "-----------" << endl;
a2 = ++a1;
cout << a2 << endl;
cout << a1 << endl;
return 0;
}