使用运算符重载实现复数的四则运算
来源:互联网 发布:vasp软件安装 编辑:程序博客网 时间:2024/05/15 23:52
程序代码:
#include <iostream>using namespace std;class Complex {public: Complex( )//定义默认构造函数初始化复数 { real=0; imag=0; } //使用初始化表初始化复数 Complex(double r, double i):real(r),imag(i){} Complex operator+(Complex &c2);//复数的加法 Complex operator-(Complex &c2);//复数的减法 Complex operator*(Complex &c2);//复数的乘法 Complex operator/(Complex &c2);//复数的除法 void display( );//显示复数private: double real;//复数的实部 double imag;//复数的虚部};//复数的加法Complex Complex::operator+(Complex &c2){ Complex c3; c3.real = real + c2.real; c3.imag = imag + c2.imag; return c3;}//复数的减法Complex Complex::operator-(Complex &c2){ Complex c3; c3.real = real - c2.real; c3.imag = imag - c2.imag; return c3;}//复数的乘法Complex Complex::operator*(Complex &c2){ Complex c3; c3.real = real*c2.real - imag * c2.imag; c3.imag = real*c2.imag + imag * c2.real; return c3;}//复数的除法Complex Complex::operator/(Complex &c2){ Complex c3; c3.real = (real * c2.real + imag * c2.imag) / (c2.real*c2.real + c2.imag * c2.imag); c3.imag = (imag * c2.real - real * c2.imag) / (c2.real*c2.real + c2.imag * c2.imag); return c3;}//显示复数void Complex::display( ){ cout<<real<<'+'<<imag<<'i'<<endl;}int main( ){ //定义三个复数 Complex c1(8,10), c2(7,2), c3; //打印第一个复数 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(); system("pause");}
执行结果:
1 1
- 使用运算符重载实现复数的四则运算
- 使用运算符重载实现复数的加法运算
- 复数类完整实现 + 四则运算符重载
- C++实现的复数运算符重载
- 实现复数类的运算符重载
- 实现复数类的运算符重载
- C++学习日记之运用运算符重载计算复数的四则运算
- 复数运算符的重载
- 通过运算符重载实现复数运算
- 复数四则运算-操作符重载
- 使用模板类实现复数的四则运算
- 面向对象复数类(class Complex) 的重载运算符 一元二元的实现与使用
- 8.1 实现复数类的运算符重载
- 项目1:实现复数类的运算符重载
- 八.1实现复数类中运算符的重载
- 9-1-实现复数的运算符重载
- 用Python重载运算符方法实现的复数类
- 用友元函数实现复数类的运算符重载
- 第2次实验——算法基本功 与 综合思考
- 集合
- swift 第一个IOS应用程序
- java从头学day03-2[函数概述]
- CoreText -- 基础
- 使用运算符重载实现复数的四则运算
- sass和less,优秀的前端样式预处理器
- android:descendantFocusability用法简析
- 细数百度公司的知名开源项目
- 6/10无聊
- ios--swift完整教程
- 雷公资本
- Eclipse Android常见错误
- 代码之谜(零)整理