标签:des style blog http color io os ar for
通过本题目的练习可以掌握成员运算符重载及友元运算符重载
要求定义一个复数类,重载加法和减法运算符以适应对复数运算的要求,重载插入运算符(<<)以方便输出一个复数的要求。
要求在主函数中创建对象时初始化对象的值。
输出数据共有4行,分别代表a,b的值和它们求和、求差后的值
无
a=3.2+4.5i b=8.9+5.6i a+b=12.1+10.1i a-b=-5.7-1.1i
#include <iostream> using namespace std; class Complex { public: Complex(double r,double i) { rm=r; im=i; } friend Complex operator +(Complex &c1,Complex &c2); friend Complex operator -(Complex &c1,Complex &c2); void display(); private: double rm,im; }; void Complex::display() { cout<<"="<<rm; if(im>=0) cout<<"+"<<im<<"i"<<endl; else cout<<im<<"i"<<endl; } Complex operator+(Complex &c1,Complex &c2) { return Complex(c1.rm+c2.rm,c1.im+c2.im); } Complex operator-(Complex &c1,Complex &c2) { return Complex(c1.rm-c2.rm,c1.im-c2.im); } int main() { Complex c1(3.2,4.5),c2(8.9,5.6); Complex c3(0,0); cout<<"a"; c1.display(); cout<<"b"; c2.display(); cout<<"a+b"; c3=c1+c2; c3.display(); cout<<"a-b"; c3=c1-c2; c3.display(); return 0; }
标签:des style blog http color io os ar for
原文地址:http://www.cnblogs.com/zhangmingcheng/p/4044245.html