[operator overloading] SDUT 1272 - Practice 10 of object-oriented programming (operator overloading)

Problem Description

Define a Complex class, overload operator "+", so that it can be used for Complex addition. The two operands involved in the operation can be class objects, or one of them can be an integer in any order. For example, c1+c2, i+c1, c1+i are all legal. (where i is an integer, c1 and c2 are a Complex number), the program realizes the sum of two Complex numbers, the sum of integer and Complex number.


There are three lines of input: the first line is the real part and the virtual part of the first complex number c1, separated by spaces. The second line is the real part and the imaginary part of the second complex c2, separated by spaces. Line 3 is the value of an integer i.


The output has three lines:
The first line is the sum of two complex numbers c1 and c2. The display mode: real part + virtual part i
The second line is the value of the first complex c1 plus i. the display mode is: real part + virtual part i
The third line is the value of i plus the first complex number c1. The display mode: real part + virtual part i

Example Input

2 3
3 5

Example Output


The comment code is overloaded + implemented: the sum of real part and real number of complex number

using namespace std;
class node
    node(double n = 0, double m = 0) {
        x = n, y = m;
    node operator + (const node &b);
    node operator + (const int b);
   // double operator + (const double b);
    friend node operator + (const int a, const node &b);
    friend ostream & operator << (ostream &out, const node &b);

    double x, y;
node node::operator + (const node &b)
    node t;
    t.x = x + b.x;
    t.y = y + b.y;
    return t;
node node::operator + (int b)
    node t;
    t.x = x + b;
    t.y = y;
    return t;
/*double node::operator+(const double b)
    double t = x + b;
    return t;
node operator + (const int a, const node &b)
    node t;
    t.x = a + b.x;
    t.y = b.y;
    return t;
ostream & operator << (ostream &out, const node &b)
    out  << b.x;
    if(b.y > 0) out  << '+';
    if(b.y != 0)
    out  << b.y << 'i' ;
    return out;
int main()
    double x, y, x1, y1;
    int num;
    cin >> x >> y >> x1 >> y1;
    node a(x, y), b(x1, y1);
    cin >> num;
    cout << a+b << endl;
    cout << a+num << endl;
    cout << num+a << endl;
  /*  double num1;
    cin >> num1;
    cout << a+num1 << endl;*/


Posted on Tue, 05 May 2020 03:18:38 -0700 by matfish