复数有两个部分:实数部分和虚数部分。假设 a=(A,Bi),c=(C,Di);则
加法:a+c = (A+C,(B+D)i)
减法:a-c = (A-C,(B-D)i)
乘法:a*c = (A*C-B*D,(A*D+B*C)i)
实属乘法:x*c=(x*C,(x*D)i)
共轭:~a=(A,Bi)
我们通过定义复数类,并对 + - * ~ >> <<等运算符进行重载,分别利用成员函数与非成员函数重载的方法。
代码如下:
complex.h文件
#ifndef COMPLEX_H_
#define COMPLEX_H_
#include<iostream>
class complex
{
public:
double real;
double imaginary;
public:
complex():real(0.0),imaginary(0.0) {}
complex(double r,double imag):real(r),imaginary(imag) {}
~complex()
{
}
complex operator + (const complex &c);
complex operator - (const complex &c);
complex operator * (const complex &c);
complex operator ~ ();
friend complex operator *(double n,complex &c);
friend std::istream & operator >> (std::istream &os,complex &c);
friend std::ostream & operator << (std::ostream &os,const complex &c);
};
#endif
complex.cpp文件 即复数类的实现
#include"complex.h"
#include<string>
complex complex::operator+(const complex &c)
{
complex temp;
temp.real=this->real+c.real;
temp.imaginary=this->imaginary+c.imaginary;
return temp;
}
complex complex::operator*(const complex &c)
{
complex temp;
temp.real=this->real*c.real-this->imaginary*c.imaginary;
temp.imaginary=this->real*c.imaginary+this->imaginary*c.real;
return temp;
}
complex complex::operator-(const complex &c)
{
complex temp;
temp.real=this->real-c.real;
temp.imaginary=this->imaginary-c.imaginary;
return temp;
}
complex complex::operator~()
{
complex temp;
temp.real=this->real;
temp.imaginary=-this->imaginary;
return temp;
}
std::istream &operator >> (std::istream &os,complex &c)
{
std::cout << "real: ";
if (!(os >> c.real))
return os;
std::cout << "imaginary: ";
if(!(os >> c.imaginary))
return os;
return os;
}
std::ostream &operator << (std::ostream & os,const complex &c)
{
os <<"("<<c.real<< ", " << c.imaginary << "i)";
return os;
}
complex operator * (double n,complex &c)
{
complex temp;
temp.real=n*c.real;
temp.imaginary=n*c.imaginary;
return temp;
}
main()函数
using namespace std;
#include "complex.h"
int main()
{
complex a(3.0,4.0);
complex c;
cout << "enter a complex number(q to quit): \n";
while(cin >> c)
{
cout << "c is " << c << endl;
cout << "complex conjugate is " << ~c <<endl;
cout << "a is " << a << endl;
cout << "a + c is "<<a + c << endl;
cout << "a -c is " << a - c << endl;
cout << "a * c" << a * c <<endl;
cout << "2 *c is " << 2 *c << endl;
cout << "enter a complex number (q to quit):" << endl;
}
cout << "done!" << endl;
return 0;
}
运行结果: