话说上次写运算符重载还是在大二,今天算是复习了
#include<iostream>
#include<math.h>
#include<string>
using namespace std;
/*
运算符重载
*/
class Complex
{
public:
Complex();
Complex(double);
Complex(double, double);
double getReal();
double getImag();
void setReal(double curReal);
void setImag(double curImag);
void showComplex();
Complex operator+ (const Complex &)const;
Complex operator- (const Complex &)const;
Complex operator* (const Complex &)const;
Complex operator/ (const Complex &)const;
// Complex operator^ (const Complex &, const Complex &);
private:
double real;
double imag;
};
Complex::Complex()
{
real = 0.0;
imag = 0.0;
}
Complex::Complex(double curReal)
{
real = curReal;
imag = 0.0;
}
Complex::Complex(double curReal, double curImag)
{
real = curReal;
imag = curImag;
}
double Complex::getReal()
{
return this->real;
}
double Complex::getImag()
{
return this->imag;
}
void Complex::setReal(double curReal)
{
this->real = curReal;
}
void Complex::setImag(double curImag)
{
this->imag = curImag;
}
void Complex::showComplex()
{
cout << this->real << " + " << this->imag << "i" << endl;
}
//const 用的不够熟练
Complex Complex:: operator+ (const Complex &c)const
{
/*报错:l-value specifies const object
real = real + c.real;
imag = imag + c.imag;
*/
Complex newComplex(real+c.real, imag+c.imag);
return newComplex;
}
Complex Complex::operator- (const Complex &c)const
{
Complex newComplex(real-c.real, imag-c.imag);
return newComplex;
}
Complex Complex::operator* (const Complex &c)const
{
Complex newComplex(real*c.real-imag*c.imag, real*c.imag+imag*c.real);
return newComplex;
}
Complex Complex::operator/ (const Complex &c)const
{
double newReal = (real*c.real-imag*c.imag)/(c.real*c.real+c.imag*c.imag);
double newImag = (imag*c.real-real*c.imag)/(c.real*c.real+c.imag*c.imag);
Complex newComplex(newReal ,newImag);
return newComplex;
}
void test()
{
Complex c1(2.3, 4.5);
Complex c2(6.7);
Complex c3;
c1.showComplex();
c2.showComplex();
c3.showComplex();
c1 = c1*c2;
c1.showComplex();
c1 = c1 + c3;
c1.showComplex();
c1 = c1 + c2;
c1.showComplex();
c1 = c1 - c2;
c1.showComplex();
c1 = c1/c2;
c1.showComplex();
}
int main()
{
test();
return 0;
}