C++ 重载
时间:2010-11-17 来源:luozhiyong131
#include <iostream.h>
class complex
{
private:
double x,y;
public:
complex(double xx=0,double yy=0)
{
x=xx; y=yy;
}
double getx()
{
return x;
}
double gety()
{
return y;
}
void display()
{
cout<<"("<<x;
if(y>0)cout<<"+"<<y<<"+i)";
else if(y<0)cout<<y<<"+i)";
else
cout<<")";
}
complex add(complex &c1,complex &c2)
{
this->x=c1.x+c2.x;this->y=c1.y+c2.y;
return *this;
}
};
void main()
{
complex c1(3,4),c2(4,-5),c3;
c3.add(c1,c2);
c1.display();
cout<<"+";
c2.display();
cout<<"=";
c3.display();
cout<<endl;
}
/******************
成员函数重载运算符+
*******************/
#include <iostream.h>
class complex
{
private:
double x,y;
public:
complex(double xx=0,double yy=0)
{
x=xx; y=yy;
}
double getx()
{
return x;
}
double gety()
{
return y;
}
void display()
{
cout<<"("<<x;
if(y>0)cout<<"+"<<y<<"+i)";
else if(y<0)cout<<y<<"+i)";
else
cout<<")";
}
complex operator + (complex &c1);
};
complex complex::operator + (complex &c1)
{
complex c;
c.x=this->x+c1.x;
c.y=this->y+c1.y;
return c;
}
void main()
{
complex c1(3,4),c2(4,-5),c3;
c3=c1+c2;
c1.display();
cout<<"+";
c2.display();
cout<<"=";
c3.display();
cout<<endl;
}
/******************
友员函数重载运算符*
*******************/
#include <iostream.h>
class complex
{
private:
double x,y;
public:
complex(double xx=0,double yy=0)
{
x=xx; y=yy;
}
double getx()
{
return x;
}
double gety()
{
return y;
}
void display()
{
cout<<"("<<x;
if(y>0)cout<<"+"<<y<<"+i)";
else if(y<0)cout<<y<<"+i)";
else
cout<<")";
}
friend complex operator * (complex &c1,complex &c2);
};
complex operator * (complex &c1,complex &c2)
{
complex c;
c.x=c2.x * c1.x;
c.y=c2.y * c1.y;
return c;
}
void main()
{
complex c1(3,4),c2(4,-5),c3;
c3=c1*c2;
c1.display();
cout<<"*";
c2.display();
cout<<"=";
c3.display();
cout<<endl;
}