- 定义并实现一个复数类complex(带两个实参的构造函数,赋值构造,默认构造),适当添加函数,使得下面的代码能够工作。
int main()
{
complex c1(3.4,5.0);
complex c2=c1;
complex c3;
c1.add(5.0); //复数c1的实部增加5.0
c2.sub(5.0); //复数c2的实部减少5.0
c3=c1.add(c2);// 复数c1和c2相加求和
c3.display(); // 显示输出复数
c3=c1.sub(c2); // 复数c1和c2相减求差
c3.display();
c3=add(c1,c2); // 复数c1和c2相加求和
c3.display();
c3=10; //复数c3的实部为10.0,虚部为0.0//类型转换函数
c3.display();
return 0;
}
#include<iostream>
#include<stdlib.h>
using namespace std;
class complex //复数类声明
{
public: //外部接口
complex(double r,double i){ real=r; imag=i;cout<<1<<endl; } //参数化构造函数
complex() { real=0.0; imag=0.0;cout<<2<<endl; } //默认构造函数
complex(complex &c){ real=c.real; imag=c.imag;cout<<3<<endl; } //复制构造函数
complex(double r) { real=r; imag=0.0;cout<<4<<endl; }//类型转换构造函数 explicit
void add(double r);
complex add(complex c);
void sub(double r);
complex sub(complex c);
void display(); //输出复数
double getreal(){ return real; }
double getimag(){ return imag; }
void setreal(double _real){ real = _real; }
void setimag(double _imag){ imag = _imag; }
private: //私有数据成员
double real; //复数实部
double imag; //复数虚部
};
void complex::add(double r)
{
real+=r;
}
complex complex::add(complex c)
{
complex result;
result.real=real+c.real;
result.imag=imag+c.imag;
return result;
// return complex(real+c.real, imag+c.imag);
}
void complex::sub(double r)
{
real-=r;
}
complex complex::sub(complex c)
{
complex result;
result.real=real-c.real;
result.imag=imag-c.imag;
return result;
// return complex(real-c.real, imag-c.imag);
}
void complex::display()
{
cout<<"("<<real<<","<<imag<<")"<<endl;
}
complex add(complex c1,complex c2)
{
double real,imag;
complex result;
real = c1.getreal() + c2.getreal();
imag = c1.getimag() + c2.getimag();
result.setreal(real);
result.setimag(imag);
return result;
// return complex(real, imag);
// return complex(c1.getreal() + c2.getreal(), c1.getimag() + c2.getimag());
}
int main() //主函数
{
complex c1(3.4,5.0);
complex c2=c1;
complex c3;
c1.add(5.0); //复数c1的实部增加5.0
c2.sub(5.0); //复数c2的实部减少5.0
c3=c1.add(c2);// 复数c1和c2相加求和
c3.display(); // 显示输出复数
c3=c1.sub(c2); // 复数c1和c2相减求差
c3.display();
c3=add(c1,c2); // 复数c1和c2相加求和
c3.display();
c3=10; //复数c3的实部为10.0,虚部为0.0
c3.display();
system("pause");
return 0;
}