第11章 使用类第7题
第7题目
复数由两个部分组成,分别是实部和虚部。 复数的一种书写方式是(3.0,4,0),其中3.0是实部,4.0是虚部。 假设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*Di)
共轭: ~a = (A,-B)
请定义一个复数类,以便下面的程序可以获得正确的结果。
complex0.h头文件:
#ifndef COMPLEX0_H_
#define COMPLEX0_H_
#include <iostream>
using std::ostream;
using std::endl;
using std::istream;
class complex
{
private:
double real; // 实部
double imag; // 虚部
public:
complex(double r=0.0,double m= 0.0);
complex operator+(const complex &c) const; // 加法
complex operator-(const complex &c) const; // 减法
complex operator*(const complex &c) const; // 数乘
complex operator~() const; // 共轭
friend complex operator*(double n, const complex &c);
friend ostream &operator<<(ostream &os, const complex &c);
friend istream &operator>>(istream &is, complex &c);
};
#endif // MACRO
complex0.cpp源文件
#include "complex0.h"
complex::complex(double r, double i) : real(r), imag(i)
{
}
complex complex::operator+(const complex &c) const
{
return complex(real+c.real,imag+c.imag);
}
complex complex::operator-(const complex &c) const
{
return complex(real-c.real,imag-c.imag);
}
complex complex::operator*(const complex &c) const
{
complex temp;
temp.real = real * c.real - imag * c.imag;
temp.imag = real*c.imag + imag * c.real;
return temp;
}
complex operator*(double n, const complex &c)
{
return complex(n*c.real, n*c.imag);
}
complex complex::operator~() const
{
return complex(real,-imag);
}
ostream &operator<<(ostream &os, const complex &c)
{
os<<"("<<c.real <<", "<<c.imag<<"i)"<< endl;
return os;
}
istream &operator>>(istream &is, complex &c)
{
std::cout << "real:";
if(!(is>>c.real))
{
return is;
}
std::cout << "imag:";
is >> c.imag;
return is;
}
主程序
#include <iostream>
using namespace std;
#include "complex0.h"
int main(int argc, char const *argv[])
{
complex a(3.0, 4.0);
complex c;
cout << "Enter a complex number (q to quit):\n" ;
while(cin >> c)
{
cout << "c is" << c << "\n";
cout << "complex conjugate is " << ~c<< "\n";
cout <<"a is "<< a << "\n";
cout << "a+c is" << a+ c << "\n" ;
cout << "a-c is" << a- c << "\n" ;
cout << "a*c is" << a* c << "\n" ;
cout << "2*c is" << 2*c << "\n" ;
cout << "Enter a complex number (q to quit):\n" ;
}
cout << "Done! \n" ;
system("pause");
return 0;
}
运行结果:
PS D:\code\cpp\C++PrimerPlusExecises\chapter11> .\out.exe
Enter a complex number (q to quit):
real:1
imag:2
c is(1, 2i)
complex conjugate is (1, -2i)
a is (3, 4i)
a+c is(4, 6i)
a-c is(2, 2i)
a*c is(-5, 10i)
2*c is(2, 4i)
Enter a complex number (q to quit):
real:33
imag:4
c is(33, 4i)
complex conjugate is (33, -4i)
a is (3, 4i)
a+c is(36, 8i)
a-c is(-30, 0i)
a*c is(83, 144i)
2*c is(66, 8i)
Enter a complex number (q to quit):
real:q
Done!