4-1 复数类的运算符重载

来源:互联网 发布:淘宝云客服报名入口 编辑:程序博客网 时间:2024/05/16 07:51

4-1 复数类的运算符重载

Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic

Problem Description

通过本题目的练习可以掌握成员运算符重载及友元运算符重载

要求定义一个复数类,重载加法和减法运算符以适应对复数运算的要求,重载插入运算符(<<)以方便输出一个复数的要求。

Input

 

要求在主函数中创建对象时初始化对象的值。

Output

 

输出数据共有4行,分别代表ab的值和它们求和、求差后的值

Example Input

Example Output

a=3.2+4.5ib=8.9+5.6ia+b=12.1+10.1ia-b=-5.7-1.1i

Author

 黄晶晶

#include<iostream>#include<algorithm>#include<cstring>using namespace std;class complx{private:    double real, imag;public:    complx(){real=imag=0;}    complx(double a, double b)    {        real=a;        imag=b;    }    complx operator +(complx &c);    complx operator -(complx &c);    void display()    {        if(imag<0)            cout<<real<<imag<<"i"<<endl;        else            cout<<real<<"+"<<imag<<"i"<<endl;    }};inline complx complx::operator+(complx &c){    return complx(real+c.real, imag+c.imag);}inline complx complx::operator-(complx &c){    return complx(real-c.real, imag-c.imag);}int main(){    ios::sync_with_stdio(false);    complx p1(3.2, 4.5), p2(8.9, 5.6), p3;    cout<<"a=";    p1.display();    cout<<"b=";    p2.display();    p3=p1+p2;    cout<<"a+b=";    p3.display();    p3=p1-p2;    cout<<"a-b=";    p3.display();    return 0;}


0 0