运算符重载—复数的计算
2016-06-13 14:49
549 查看
/* *Copyright (c) 2016 烟台大学计算机与控制工程学院 *All rights reserved. *文件名称:test.cpp *作 者:史红浩 *完成日期:2016年 6 月 13 日 *版 本 号:v1.0 */ #include<iostream> #include <iomanip> using namespace std; class Complex { public: Complex(){real=0;imag=0;} Complex(double r,double i){real=r; imag=i;} Complex operator+(const Complex &c2); Complex operator-(const Complex &c2); Complex operator*(const Complex &c2); Complex operator/(const Complex &c2); void display(); private: double real; double imag; }; //下面定义成员函数 Complex Complex::operator+(const Complex &c2) { Complex c; c.real=real+c2.real; c.imag=imag+c2.imag; return c; } Complex Complex::operator-(const Complex &c2) { Complex c; c.real=real-c2.real; c.imag=imag-c2.imag; return c; } Complex Complex::operator*(const 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/(const Complex &c2) { Complex c; c.real=(real*c2.real+imag*c2.imag)/(real*real+c2.imag*c2.imag); c.imag=(imag*c2.real-real*c2.imag)/(real*real+c2.imag*c2.imag); return c; } void Complex::display() { if(real!=0&&imag>0) cout<< fixed << setprecision(2)<<real<<"+"<<imag<<"i"<<endl; if(real!=0&&imag<0) cout<< fixed << setprecision(2)<<real<<imag<<"i"<<endl; if(real==0&&imag!=0) cout<< fixed << setprecision(2)<<imag<<"i"<<endl; if(imag==0&&real!=0) cout<< fixed << setprecision(2)<<real<<endl; if(imag==0&&real==0) cout<< fixed << setprecision(2)<<"0"<<endl; } //下面定义用于测试的main()函数 int main() { Complex c1(3,4),c2(5,-10),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(); return 0; }
运行结果:
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android Native 绘图方法
- Python动态类型的学习---引用的理解
- 关于指针的一些事情
- 肯特·贝克:改变人生的代码整理魔法
- 你应该学习哪种编程语言?
- c++ primer 第五版 笔记前言
- [转]我们需要一种其他人能使用的编程语言
- share_ptr的几个注意点
- DB2编程序技巧(1)
- DB2编程序技巧 (四)
- 女人VS编程_国庆快乐
- DB2编程序技巧 (六)
- DB2编程序技巧 (三)
- DB2编程序技巧 (九)
- DB2编程序技巧 (七)
- DB2编程序小小技巧
- DB2编程序技巧 (五)
- 土人系列AS入门教程 -- 对象篇
- DB2编程序技巧 (一)