面向对象程序设计上机练习十(运算符重载)

来源:互联网 发布:徐水网络互动 编辑:程序博客网 时间:2024/05/18 00:30

面向对象程序设计上机练习十(运算符重载)

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

Problem Description

定义一个复数类Complex,重载运算符“+”,使之能用于复数的加法运算。参加运算的两个运算量可以都是类对象,也可以其中有一个是整数,顺序任意。例如:c1+c2、i+c1、c1+i均合法。(其中i是整数,c1、c2是复数),编程实现求2个复数之和、整数与复数之和。

Input

输入有三行:第1行是第1个复数c1的实部和虚部,以空格分开。第2行是第2个复数c2的实部和虚部,以空格分开。第3行是1个整数i的值。

Output

输出有三行:
第1行是2个复数c1和c2的和,显示方式:实部+虚部i
第2行是第1个复数c1加i的值,显示方式:实部+虚部i 
第3行是i加第1个复数c1的值,显示方式:实部+虚部i

Example Input

2 33 510

Example Output

5+8i12+3i12+3i

Hint

Author

方法一:只对+重载
#include <iostream>using namespace std;class Complex{private:    int real;    int imag;public:    Complex(int re = 0, int im = 0)    {        real = re;        imag = im;    }    Complex operator + (Complex & c2)    {        Complex c;        c.real = real + c2.real;        c.imag = imag + c2.imag;        return c;    }    Complex operator + (int x)    {        Complex c;        c.real = real + x;        c.imag = imag;        return c;    }    friend Complex operator + (int x, Complex & c2)    {        Complex c;        c.real = x + c2.real;        c.imag = c2.imag;        return c;    }    void show()    {        cout << real << "+" << imag << "i" << endl;    }};int main(){    int x1, x2, y1, y2, x;    cin >> x1 >> y1;    cin >> x2 >> y2;    cin >> x;    Complex c1(x1, y1);    Complex c2(x2, y2);    Complex c3 = c1 + c2;    Complex c4 = c1 + x;    Complex c5 = x + c1;    c3.show();    c4.show();    c5.show();    return 0;}

方法二:对+和<<全部重载
#include <iostream>using namespace std;class Complex{private:    int real;    int imag;public:    Complex(int re = 0, int im = 0)    {        real = re;        imag = im;    }    Complex operator + (Complex & c2)    {        Complex c;        c.real = real + c2.real;        c.imag = imag + c2.imag;        return c;    }    Complex operator + (int x)    {        Complex c;        c.real = real + x;        c.imag = imag;        return c;    }    friend Complex operator + (int x, Complex & c2)    {        Complex c;        c.real = x + c2.real;        c.imag = c2.imag;        return c;    }    friend ostream & operator << (ostream & output, Complex c)      //对输出流<<重载,也可以不用    {        cout << c.real << "+" << c.imag << "i" << endl;    }};int main(){    int x1, x2, y1, y2, x;    cin >> x1 >> y1;    cin >> x2 >> y2;    cin >> x;    Complex c1(x1, y1);    Complex c2(x2, y2);    Complex c3 = c1 + c2;    Complex c4 = c1 + x;    Complex c5 = x + c1;    cout << c3 << c4 << c5;    return 0;}



0 0