法一:友元函数
#include<iostream>
#include<cmath>
using namespace std;
class Complex
{
public:
Complex()
{
real=0;
imag=0;
}
Complex(float re,float im)
{
real=re;
imag=im;
}
Complex(float re)//如果用这种方法,那么complex就不能用引用
{
real=re;
imag=0;
}
friend Complex operator+(const Complex c1,const Complex c2);//只有声明为友元函数,才可以引用两个参数
friend Complex operator-(const Complex c1,const Complex c2);
friend ostream &operator<<(ostream &outs,const Complex &B);
friend istream &operator>>(istream &ins,Complex &C)
{
ins>>C.real>>C.imag;
}
private:
float real;
float imag;
float x;
};
Complex operator+(const Complex c1,const Complex c2)//友元函数的类型是Complex
{
return Complex(c1.real+c2.real,c1.imag+c2.imag);
}
Complex operator-(const Complex c1,const Complex c2)
{
return Complex(c1.real-c2.real,c1.imag-c2.imag);
}
ostream &operator<<(ostream&outs,const Complex &B)
{
if(B.imag>0)
outs<<"("<<B.real<<","<<B.imag<<"i)"<<"\n";
else
outs<<"("<<B.real<<","<<B.imag<<"i)"<<"\n";
}
int main( )
{
Complex c1(5.0,10.0); //5+10i
Complex c2(3.0,-2.5); //3-2.5i
Complex c3,c4;
c3=c1+c2;
c4=c1-5;
cout<<c1<<c2<<c3<<c4;
Complex c5;
cout<<"请输入一个复数,实部和虚部以空格分开:"<<endl;
cin>>c5;
cout<<"输入的复数为:"<<c5<<endl;
c4=5+c5;
cout<<c4<<endl;
return 0;
}
法二:成员函数
最基础的(最笨的,最麻烦)
#include<iostream>
using namespace std;
class Complex
{public:
Complex()
{
real=0;
imag=0;
}
Complex(float re,float im)
{
real=re;
imag=im;
}
//成员函数,负数直接相加减
Complex operator+(const Complex &c);
Complex operator-(const Complex &c);
//浮点数与负数之间的加减,涉及到两个参数,需要用友元函数
friend Complex operator+(const Complex &c,float hh);
friend Complex operator+(float hh,const Complex &c);
friend Complex operator-(const Complex &c,float hh);
friend Complex operator-(float hh,const Complex &c);
friend ostream &operator<<(ostream &outs,const Complex &B);
friend istream &operator>>(istream &ins,Complex &C)
{
ins>>C.real>>C.imag;
}
protected:
float real;
float imag;
};
Complex Complex::operator+(const Complex &c)
{
return Complex(real+c.real,imag+c.imag);
}
Complex Complex::operator-(const Complex &c)
{
return Complex(real-c.real,imag-c.imag);
}
Complex operator+(const Complex &c,float hh)//类型是Complex
{
return Complex(c.real+hh,c.imag);
}
Complex operator+(float hh,const Complex &c)//类型是Complex
{
return Complex(c.real+hh,c.imag);
}
Complex operator-(const Complex &c,float hh)//类型是Complex
{
return Complex(c.real-hh,c.imag);
}
Complex operator-(float hh,const Complex &c)//类型是Complex
{
return Complex(hh-c.real,c.imag);
}
//输入输出流,只能为友元函数
ostream &operator<<(ostream&outs,const Complex &B)
{
if(B.imag>0)
outs<<"("<<B.real<<","<<B.imag<<"i)"<<"\n";
else
outs<<"("<<B.real<<","<<B.imag<<"i)"<<"\n";
}
int main( )
{
Complex c1(5.0,10.0); //5+10i
Complex c2(3.0,-2.5); //3-2.5i
Complex c3,c4;
c3=c1+c2;
c4=c1-5;
cout<<c1<<c2<<c3<<c4;
Complex c5;
cout<<"请输入一个复数,实部和虚部以空格分开:"<<endl;
cin>>c5;
cout<<"输入的复数为:"<<c5<<endl;
c4=5+c5;
cout<<c4<<endl;
return 0;
}
“我踏碎万家灯火来寻你,山河璀璨权作聘礼”