64,683
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
class Complex;
Complex operator + (Complex a,Complex b);
Complex operator - (Complex a,Complex b);
Complex operator + (Complex a,double r);
Complex operator - (Complex a,double r);
class Complex
{
friend Complex operator + (Complex a,Complex b);
friend Complex operator - (Complex a,Complex b);
friend Complex operator + (Complex a,double r);
friend Complex operator - (Complex a,double r);
public:
Complex (Complex &a);
Complex (double r=0,double i=0);
void display();
private:
double real;
double img;
};
Complex::Complex(Complex &a)
{
real = a.real;
img = a.img;
}
Complex::Complex(double r,double i)
{
real = r;
img = i;
}
void Complex::display()
{
cout << real <<(img>=0?"+":"")<<img<<"i"<<endl;
}
Complex operator +(Complex a,Complex b)
{
Complex temp(a.real+b.real,a.img+b.img);
return temp;
}
Complex operator -(Complex a,Complex b)
{
Complex temp(a.real-b.real,a.img-b.img);
return temp;
}
Complex operator +(Complex a,double r)
{
Complex temp(a.real+r,a.img);
return temp;
}
Complex operator -(Complex a,double r)
{
Complex temp(a.real-r,a.img);
return temp;
}
int main()
{
Complex a(3,2),b(5,4),c(1,1),d(4,2),temp;
//temp = a+b;
//temp.display();
//temp = a-b;
//temp.display();
temp = a+b-(c+d);
temp.display();
return 0;
}
#include <iostream>
using namespace std;
class CTest
{
public:
CTest();
CTest(const int&,const int&);
CTest& operator+(const CTest& a);
CTest& operator-(const CTest& a);
void display();
private:
double real;
double img;
};
CTest::CTest()
{
}
CTest::CTest(const int& a,const int& b):real(a),img(b)
{
}
CTest& CTest::operator+(const CTest& a)
{
this->img += a.img;
this->real += a.real;
return *this;
}
CTest& CTest::operator-(const CTest& a)
{
this->img -= a.img;
this->real -= a.real;
return *this;
}
void CTest::display()
{
cout<<"real = "<<real<<endl;
cout<<"img = "<<img<<endl;
}
int main()
{
CTest a(3,2),b(5,4),c(1,1),d(4,2),temp;
temp = a+b-(c+d);
temp.display();
return 0;
}