华侨大学2009C++试卷
2、设计并测试复数类(Complex)
(1) 设计一个复数类(Complex)包含两个数据成员:实部(real),虚部(imagin);
包含如下主要成员函数:
• 构造函数(用来初始化一个复数对象,默认实部、虚部均为0);
• 重载加、减法运算符(+、-)实现复数类的加、减法运算;
• 显示复数对象,按a+bi(a为实部、b为虚部)格式输出一个复数对象。
(2) 请在主函数中使用所设计的复数类定义两个复数对象,求其和、差并输出。
#include<iostream>
using namespace std;
class Complex{
private:
int real;
int imagin;
public:
Complex(){
real = 0;
imagin = 0;
}
Complex(int a, int b){
real = a;
imagin = b;
}
// friend Complex operator+(const Complex& c1, const Complex& c2);
// friend Complex operator-(const Complex& c1, const Complex& c2);
friend ostream& operator<<(ostream& cout, Complex& c);
Complex operator+(const Complex& c){
Complex temp;
temp.real = this->real + c.real;
temp.imagin = this->imagin + c.imagin;
return temp;
}
Complex operator-(const Complex& c){
Complex temp;
temp.real = this->real - c.real;
temp.imagin = this->imagin - c.imagin;
return temp;
}
void display(){
if(this->real != 0 && this->imagin != 0){
cout << this->real << "+" <<this->imagin << "i" << endl;
}else if(this->imagin == 0){
cout << this->real << endl;
}else{
cout << this->imagin << "i" << endl;
}
}
//自己增加的求积
/**
3、乘法法则
规定复数的乘法按照以下的法则进行:
设z1=a+bi,z2=c+di(a、b、c、d∈R)是任意两个复数,那么它们的积(a+bi)(c+di)=(ac-bd)+(bc+ad)i。
*/
Complex operator*(const Complex& c){
Complex temp;
// if(this->imagin != 0 && c.imagin != 0){//虚部不为0时
// temp.real = (this->real * c.real) - (this->imagin * c.imagin);//两个虚部相乘是负数
// temp.imagin = (this->imagin * c.real) + (this->real * c.imagin);
// }
// else{//当有其中一个虚部为0时
// temp.real = (this->real * c.real);
// temp.imagin = (this->imagin * c.real) + (this->real * c.imagin);
// }
temp.real = (this->real * c.real) - (this->imagin * c.imagin);
temp.imagin = (this->imagin * c.real) + (this->real * c.imagin);
return temp;
}
};
//Complex operator+(const Complex& c1, const Complex& c2){
// Complex temp;
// temp.real = c1.real + c2.real;
// temp.imagin = c1.imagin + c2.imagin;
// return temp;
//}
//
//Complex operator-(const Complex& c1, const Complex& c2){
// Complex temp;
// temp.real = c1.real - c2.real;
// temp.imagin = c1.imagin - c2.imagin;
// return temp;
//}
ostream& operator<<(ostream& cout, Complex& c){
if(c.real != 0 && c.imagin != 0){
cout << c.real << "+" <<c.imagin << "i" << endl;
}else if(c.imagin == 0){
cout << c.real << endl;
}else{
cout << c.imagin << "i" << endl;
}
}
int main(){
Complex c1(1,2),c2(3,4), c3, c4, c5;
c3 = c1 + c2;
c4 = c1 - c2;
c5 = c1 * c2;
c3.display();
c4.display();
c5.display();
return 0;
}