概述
定义复数类Complex,包括两个double型的数据成员real和image,要求对+、-、、/、+=、-+、=、/=、几个运算符进行重载以实现复数的运算,并进行验证。
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class Complex
{
public:
//默认的构造函数(含缺省值,并初始化参数)
Complex(const double real = 0.0, const double image = 0.0)
:_real(real) //初始化
, _image(image)
{}
//拷贝构造函数
Complex(const Complex& c)
{
_real = c._real;
_image = c._image;
}
//析构函数
~Complex()
{}
//赋值运算符的重载
Complex& operator=(const Complex& c)
{
this->_real = c._real;
//_real = c._real;//隐含的this指针
this->_image = c._image;
//_image = c._image;
return *this;
}
//加法运算符的重载
Complex operator+(const Complex& c)
{
Complex tmp;
tmp._real = _real + c._real;
tmp._image = _image + c._image;
return tmp;
}
//减法
Complex operator-(const Complex& c)
{
Complex tmp;
tmp._real = _real - c._real;
tmp._image = _image - c._image;
return tmp;
}
//乘法
Complex operator*(const Complex& c)
{
Complex tmp;
tmp._real = _real * c._real - _image*c._image;
tmp._image = _real * c._image + _image*c._real;
return tmp;
}
//除法
Complex operator/(const Complex& c)
{
Complex tmp;
tmp._real = (_real / c._real + _image*c._image) / (c._real*c._real + c._image*c._image);
tmp._image = (_image*c._real - _real*c._image) / (c._real*c._real + c._image*c._image);
return tmp;
}
Complex operator+=(const Complex& c)
{
_real += c._real;
_image += c._image;
return *this;
}
Complex operator-=(const Complex& c)
{
_real -= c._real;
_image -= c._image;
return *this;//返回当前对象
}
Complex operator*=(const Complex& c)
{
double real0 = _real;
double image0 = _image;
_real = (real0 * c._real - image0*c._image);
_image = (real0 * c._image + image0*c._real);
return *this;
}
Complex operator/=(const Complex& c)
{
double real0 = _real;
double image0 = _image;
_real /= (real0 / c._real + image0*c._image) / (c._real*c._real + c._image*c._image);
_image /= (image0*c._real - real0*c._image) / (c._real*c._real + c._image*c._image);
return *this;
}
void Display()
{
cout << _real << " " << _image << endl;
}
private:
double _real;
double _image;
};
//测试函数
void Funtest1()
{
Complex c1(2.0, 3.0);
c1.Display();
Complex c2(c1);
c2.Display();
Complex c3;
c3 = c1+c2;
c3.Display();
}
void Funtest2()
{
Complex c1(2.0, 3.0);
c1.Display();
Complex c2(c1);
c2.Display();
c1 *= c2;
c1.Display();
}
int main()
{
cout << "Funtest1:" << endl;
Funtest1();
cout << "Funtest2:" << endl;
Funtest2();
getchar();
return 0;
}
运行结果
最后
以上就是感动犀牛为你收集整理的复数类 complex的全部内容,希望文章能够帮你解决复数类 complex所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复