#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
/*6. 更加完整建立一个复数类 Complex,要求
a. 含两个私有数据成员:real, imaginary: float
b. 具有三种构造函数:a.不带参数构造: 0+0i
b.以实部和虚部构造
c.拷贝构造函数
c.公有成员函数包括如下功能:
输出这个复数
与另一复数的加法函数,要求函数原型为 complex add(complex c);
判断与另一复数是否相等 要求函数原型为bool isEqual(complex c);
在main函数中,输入两个复数,判断两个复数是否相等(实部和虚部要分别相等),然后两者相加之和赋值给一个新的复数,并输出
思考:基于上面的Complex类,有如下main函数能否通过运行,有那些是错误的,为什么?
int main()
{
Complex a,b;
Complex c=a+b;
Complex d=a;
Complex e;
e=a;
return 0;
}*/
class Complex{
public:
void getRI(float R,float I); //设置复数的两个私有成员
void output(); //输出这个复数
void add(Complex c); //与另一复数的加法函数 原型为 add (Complex c);
void isEqual(Complex c); //判断与另一复数是否相等
Complex(){ //不带参数的构造函数
real=0;
imaginary=0;
}
Complex(float R,float I); //以实部和虚部构造
Complex(Complex &c); //复制构造函数
Complex operator+(Complex& b)
{
real += b.real;
imaginary += b.imaginary;
return *this;
}
private:
float real,imaginary;
};
Complex::Complex(float R,float I) //带参数构造函数的实现
{
real=R;
imaginary=I;
}
Complex::Complex(Complex &c){
real=c.real;
imaginary=c.imaginary;
cout<<"calling the copy constructor"<<endl;
}
void Complex::getRI(float R,float I){
real=R;
imaginary=I;
}
void Complex::output(){
cout<<real<<"+"<<imaginary<<"i"<<endl;
}
void Complex::add(Complex c){
cout<<"两复数相加为:";
cout<<real+c.real<<"+"<<imaginary+c.imaginary<<"i"<<endl;
}
void Complex::isEqual(Complex c){
if(real==c.real)
{
if(imaginary==c.imaginary)
cout<<"They are equal."<<endl;
}
else
cout<<"They are not equal."<<endl;
}
int main(int argc, char** argv) {
Complex c1;
Complex c2(1,2); //调用带参数的构造函数
Complex c3(3,4); //用对象c2初始化对象c3,复制构造函数被调用
float R1,I1,R2,I2;
cin>>R1>>I1;
cin>>R2>>I2;
c2.getRI(R1,I1);
c3.getRI(R2,I2);
cout<<"复数c2为:";
c2.output();
cout<<"复数c3为:";
c3.output();
c2.add(c3);
c2.isEqual(c3);
/*函数调用的时候不用
也不可以包含两类型名,
应该写成myComplex.add(c); */
Complex a,b;
Complex c=a+b;
Complex d=a;
Complex e;
e=a;
return 0;
}