Practice 10 on object programming (operator overloading)

#include<bits/stdc++.h>
using namespace std;
class point
{
public :
     point (int r=0,int i=0):real(r),image(i){}
     point operator +(point &c1);
     point operator +(int r);
     friend point operator +(int r,point &c2);
     friend ostream  &operator <<(ostream &ouput,point &c);
     friend istream &operator>>(istream &input,point &c);
private:
    int real,image;
};
point point ::operator+(point &c1)
{
    point c;
    c.real=real+c1.real;
    c.image=image+c1.image;
    return c;
}
point point ::operator+(int r)
{
    point c;
    c.real=real+r;
    c.image=image;
    return c;
}
 point operator +(int r,point &c2)
{
    point c1;
    c1.real=r+c2.real;
    c1.image=c2.image;
    return c1;
}
 ostream &operator<<(ostream &output,point &c)
{
    if(c.image>0)
    {
        output<<c.real<<"+"<<c.image<<"i"<<endl;
    }
    else
    {
        output<<c.real<<c.image<<"i"<<endl;
    }
    return output;

}
int main()
{
    int a,b,c,d,i;
    cin>>a>>b>>c>>d;
    cin>>i;
    point p1(a,b);
    point p2(c,d);
    point p3;
    p3=p1+p2;
    cout<<p3;
    point p4;
    p4=p1+i;
    cout<<p4;
    point p5;
    p5=i+p1;
    cout<<p5;
    return 0;
}

Practice 10 on object programming (operator overloading)
Time Limit: 1000MSMemory Limit: 65536KB
SubmitStatistic

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.

Input

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.

Output

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
10

Example Output

5+8i
12+3i
12+3i
 

Tags: P4 Programming

Posted on Sun, 03 May 2020 11:51:06 -0700 by DataSpy