作者在 2011-06-10 13:48:52 发布以下内容
#include <iostream>
using namespace std;
class complex
{
public:
complex(){cout<<"调用构造函数"<<endl;}
complex(int r,int i);
complex(complex&c);
void set_c(int r,int i);
int get_c();
// void add(complex &c1,complex &c2); //使用普通函数实现两个复数的相加;
complex operator +(complex &c1); //使用重载运算符函数“+”实现两个复数的相加;
private:
int real;
int imag;
};
complex::complex(complex&c)
{
real=c.real;
imag=c.imag;
cout<<"调用复制构造函数"<<endl;
if(imag>0)
cout<<real<<"+"<<imag<<"i"<<endl;
else
if(imag=0)cout<<real<<endl;
else
cout<<real<<imag<<"i"<<endl;
}
complex::complex(int r,int i)
{
real=r;imag=i;
cout<<"调用带参数的构造函数"<<endl;
if(imag>0)
cout<<real<<"+"<<imag<<"i"<<endl;
else
if(imag=0)cout<<real<<endl;
else
cout<<real<<imag<<"i"<<endl;
}
void complex:: set_c(int r,int i)
{
real=r;
imag=i;
}
int complex::get_c()
{
if(imag>0)
cout<<real<<"+"<<imag<<"i"<<endl;
else
if(imag=0)cout<<real<<endl;
else
cout<<real<<imag<<"i"<<endl;
return 0;
}
/*void complex::add(complex &c1,complex &c2)
{
real=c1.real+c2.real;
imag=c1.imag+c2.imag;
if(imag>0)
cout<<real<<"+"<<imag<<"i"<<endl;
else
if(imag=0)cout<<real<<endl;
else
cout<<real<<imag<<"i"<<endl;
} */
complex complex:: operator +(complex &c1) //重载运算符函数“+”函数的定义部分,参数只有一个,原因:默认的第一个操作数
{
complex c; // 本对象,因此只有一个操作数;其他的香类似。。
c.real=real+c1.real;
c.imag=imag+c1.imag;
return c;
}
int main()
{
complex c1;
c1.set_c(2,3);
c1.get_c();
cout<<endl<<endl;
complex c2(c1);
cout<<endl<<endl;
complex c3(4,6);
cout<<endl<<endl;
complex c4;
cout<<"复数相加后的结果为:";
// c4.add(c3,c1); //普通add()函数的相加功能;
cout<<endl<<endl;
complex c5;
cout<<"运用重载运算符函数执行的相加功能得出的结果是:";
c5=c1+c2; //利用重载运算符函数“+”实现两个复数的相加功能
system("pause");
return 0;
}