使用c++定义一个复数类,设计相应的构造函数及成员函数,在主函数种定义复数对象,进行复数之间的加法运算
1个回答
展开全部
#include<iostream>
using namespace std;
/*
1.同一个运算符可以代表多个不同的功能,编译系统是根据操作的数据来判别该执行具体哪一个功能的
*/
class complex
{
public:
complex(){ real = 0; imag = 0; } //有参和无参的构造函数
complex(double r, double i){ real = r; imag = i; }
//当运算符重载为类的成员函数时的时候,函数的参数的个数要比原来的操作数少一个(后置“++”、“-”除外),因为成员函数都是通过该类的某个对象来访问的,成员函数中有一隐含的参数this指针,this指针
//指向当前的对象,而当前的对象本身就是其中的一个操作数。
//当运算符重载为友元函数的时候,参数的个数与原来的操作数目是一样的
complex operator+(complex &c2);//运算符的重载。因为本身的‘+’只能是对基本类型数据进行操作,现在想要对复数类也进行操作。那么必须要重载,重新定义其为我们需要的功能
complex operator-(complex &c2);
complex operator*(complex &c2);
complex operator/(complex &c2);
complex operator+(int &i);
complex operator-(int &i);
complex operator*(int &i);
complex operator/(int &i);
void display();
private:
double real;
double imag;
};
//不明白为什么这里的return不能像后面复数与整数相加时的return.
//解答:还不都是一样的,只不过是因为前面涉及到了实部和虚部操作,因此重新构造一个复数类的对象会使程序更加明了。
//后面只是用到了实部,因此不需要浪费内存空间,重新申请一个新的复数类的对象(乘除除外)。程序简化为直接创建一个临时的无名对象作为返回值,程序的运行效率更高
//复数和复数的操作运算
complex complex::operator+(complex &c2)
{
complex c;
c.real = real + c2.real;
c.imag = imag + c2.imag;
return c;
}
complex complex::operator-(complex &c2)
{
complex c;
c.real = real - c2.real;
c.imag = imag - c2.imag;
return c;
}
complex complex::operator *(complex &c2)
{
complex c;
c.real = real*c2.real - imag*c2.imag;
c.imag = imag*c2.real + real*c2.imag;
return c;
}
complex complex::operator / (complex &c2)
{
complex c;
c.real = (real*c2.real + imag*c2.imag) / (c2.real*c2.real + c2.imag*c2.imag);
c.imag = (imag*c2.real - real*c2.imag) / (c2.real*c2.real + c2.imag*c2.imag);
return c;
}
//复数与整数之间的操作
complex complex::operator +(int &i)
{
return complex(real + i, imag);
}
complex complex::operator -(int &i)
{
return complex(real - i, imag);
}
complex complex::operator *(int &i)
{
return complex(real*i, imag*i);
}
complex complex::operator /(int &i)
{
return complex(real / i, imag / i);
}
void complex::display()
{
cout << "(" << real << "," << imag << "i)" << endl;
}
int main()
{
complex c1(1, 2), c2(3, 4), c3;
int i = 5;
cout << "c1=";
c1.display();
cout << "c2=";
c2.display();
c3 = c1 + c2;
cout << "c1+c2=";
c3.display();
c3 = c1 - c2;
cout << "c1-c2=";
c3.display();
c3 = c1*c2;
cout << "c1*c2=";
c3.display();
c3 = c1 / c2;
cout << "c1/c2=";
c3.display();
cout << "i=" << i << endl;
c3 = c1 + i;
cout << "c1+i=";
c3.display();
c3 = c1 - i;
cout << "c1-i=";
c3.display();
c3 = c1*i;
cout << "c1*i=";
c3.display();
c3 = c1 / i;
cout << "c1/i=";
c3.display();
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询