Overload Operators

  • + 0 comments

    class Complex { private: int real; int imag;

    public:
    Complex(int r = 0, int i = 0)
    {
        real = r;
        imag = i;
    
    }
    
    Complex(const string& s)
    {
        int pos;
        pos = s.find('i');
        if(pos!= string::npos)
        {
            real = stoi(s.substr(0,pos-1));
            imag = stoi(s.substr(pos+1));
            if(s[pos-1] == '-')
            {
                imag = - imag;
            }
        }
    }
    
    Complex operator + (Complex const & Obj)
    {
        Complex res;
        res.real = real + Obj.real;
        res.imag = imag + Obj.imag;
        return res;
    }
    
    void print() { cout << real << "+i" << imag << '\n'; }
    

    }; int main() {

    string s1, s2;
    cin >> s1>>s2;
    
    Complex c1(s1);
    Complex c2(s2);
    
    Complex c3 = c1 + c2;
    
    c3.print();
    
    return 0;
    

    }