【c++】用c++实现复数类及运算符的重载
2017-09-21 18:26
543 查看
#include<iostream> using namespace std; class Complex { public: Complex(double real = 0.0, double image = 0.0)//构造函数 :_real(real) , _image(image) { } Complex(const Complex& c)//拷贝构造函数 { _real = c._real; _image = c._image; } Complex& operator=(const Complex& c)// =赋值运算符重载 { if (this != &c) { _real = c._real; _image = c._image; } return *this; } Complex operator+(const Complex& c)// +的重载 { Complex temp; temp._real = _real + c._real; temp._image = _image + c._image; return temp; } Complex operator-(const Complex& c)// - 的重载 { Complex temp; temp._real = _real - c._real; temp._image = _image - c._image; return temp; } Complex operator*(const Complex& c)// * 的重载 { Complex temp; temp._real = _real*c._real - _image*c._image; temp._image = _real*c._image + _image*c._real; return temp; } Complex operator/(const Complex& c)// /的重载 { Complex temp; temp._real = (_real*c._real - _image*c._image) / (c._real*c._real + c._image*c._image); temp._image = (_real*c._image + _image*c._real) / (c._real*c._real + c._image*c._image); return temp; } Complex* operator+=(const Complex& c)//+= 的重载 { _real = _real + c._real; _image =_image + c._image; return this; } Complex* operator-=(const Complex& c)//-= 的重载 { _real = _real -c._real; _image = _real - c._image; return this; } Complex *operator*=(const Complex& c)//*= 的重载 { _real = _real*c._real - _image*c._image; _image = _real*c._image + _image*c._real; return this; } Complex* operator/=(const Complex& c)// /= 的重载 { _real = (_real*c._real - _image*c._image) / (c._real*c._real + c._image*c._image); _image = (_real*c._image + _image*c._real) / (c._real*c._real + c._image*c._image); return this; } private: double _real;//复数实部 double _image;//复数虚部 }; int main()//主函数内进行测试验证 { Complex d1(2.0, 3.0); Complex d2(4.0 ,5.0); Complex d3; //d3 = d1 + d2; //d3 = d1 - d2; //d3 = d1*d2; //d3 = d1 / d2; //d1 += d2; //d1 -= d2; //d1 *= d2; d1 /= d2; return 0; }
相关文章推荐
- 【C++】模拟实现一个复数类,要求实现 加,减,乘,除等基本运算符的重载
- 8-1-2友元函数实现复数运算符的重载
- 八.1实现复数类中运算符的重载
- 利用友元函数实现复数中运算符的重载
- 通过重载输入和输出运算符实现复数的输入和输出
- 第九周 C++任务一。定义Complex类中的<<和>>运算符的重载,实现输入和输出
- 15第八周项目一——实现复数类中的运算符的重载(完整类)
- 第8周项目1(2)—用友元函数实现复数类运算符重载
- 第8周项目1-1实现复数类中的运算符重载
- 《C++第九周实验报告1-1》--------接第8周任务1,定义Complex类中的<<和>>运算符的重载,实现输入和输出
- C++第九周【任务一】定义Complex类中的<<和>>运算符的重载,实现输入和输出
- 【c++】实现运算符的重载
- C++重载加号运算符实现两个结构体的相加
- c++第八周【任务1-1】实现复数类中的运算符重载
- c++日期类的实现级运算符的重载
- 浅谈C++中用友元函数的方法实现复合运算符(+=等)的重载方法
- 洗刷刷——实现复数运算中+运算符的重载
- C++之运算符的重载实现大数的运算
- c++通过运算符[]重载实现一重和二重数组
- C++重载加号运算符实现两个结构体的相加