//功能:设计一个复数类, 给出构造函数、析构函数、拷贝构造函数、两个复数相加、两个复数相减、以(a,b)格式输出的成员函数,并设计一个函数实现复数的加减运算。 |
#include <iostream> |
using namespace std; |
class Complex //定义一个复数类 |
{ |
public : |
Complex( double a0=0, double b0=0) //构造函数 |
{ |
real=a0; |
imaginary=b0; |
} |
|
Complex(Complex& c) //拷贝构造函数 |
{ |
real=c.real; |
imaginary=c.imaginary; |
} |
|
~Complex(){} //析构函数 |
|
void show() //输出函数 |
{ |
cout<< "(" <<real<< "," <<imaginary<< ")" <<endl; |
} |
|
Complex add(Complex c2) //两个复数相加函数 |
{ |
Complex c; |
c.real=real+c2.real; |
c.imaginary=imaginary+c2.imaginary; |
return c; |
} |
|
Complex plus(Complex c2) //两个复数相减函数 |
{ |
Complex c; |
c.real=real-c2.real; |
c.imaginary=imaginary-c2.imaginary; |
return c; |
} |
private : |
double real,imaginary; |
}; |
int main() |
{ |
//输入 |
double a1,b1,a2,b2; |
|
cout<< "请输入第一个复数实部和虚部:" ; |
cin>>a1>>b1; |
|
cout<< "请输入第二个复数实部和虚部:" ; |
cin>>a2>>b2; |
|
|
//计算 |
Complex c1(a1,b1),c2(a2,b2),c3,c4; |
c3=c1.add(c2); |
cout<< "两复数之和:" ; |
c3.show(); |
cout<< "两复数之差:" ; |
c4=c1.plus(c2); |
c4.show(); |
return 0; |
} |