Overload Operators

Sort by

recency

|

137 Discussions

|

  • + 0 comments

    include

    include

    include

    include

    include

    using namespace std; class Complex { public: int real, imag; // Constructor of initially value set Complex(int r = 0, int i = 0) { real = r; imag = i; } // Complex overloading Complex operator + (Complex const &obj) { Complex res; res.real = real + obj.real; res.imag = imag + obj.imag; return res; } void display() { cout << real << "+" << imag << "i" << endl; } };

    int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ Complex c1(3, 4), c2(5, 6);

    Complex c3 = c1 + c2;
    
    c3.display();   
    return 0;
    

    }

  • + 0 comments
    Complex operator+(const Complex &a, const Complex &b)
    {
        Complex result;
        result.a = a.a + b.a;
        result.b = a.b + b.b;
        return result;
    };
    
    ostream &operator<<(ostream &os, const Complex a)
    {
        os << a.a << "+i" << a.b << endl;
        return os;
    };
    
  • + 0 comments

    Very good points you wrote here. This is a powerful feature in object-oriented programming languages like C++ and Python, enabling intuitive expressions and operations on custom objects. Betguru Login ID and Password

  • + 0 comments

    include

    include

    include

    include

    include

    using namespace std; class Complex{ public: int real,imag; void input(){ string input; cin >> input;

    size_t i_pos = input.find('i');
    if (i_pos != string::npos) {
        size_t sign_pos = input.find("+i");
        if (sign_pos == string::npos)
            sign_pos = input.find("-i");
        if (sign_pos != string::npos) {
            real = stoi(input.substr(0, sign_pos)); 
            imag = stoi(input.substr(sign_pos + 2)); 
            if (input[sign_pos] == '-')
                imag = -imag;
        }
        }
    }
    Complex operator+(const Complex& other )
    {
        Complex result;
        result.real=this->real+other.real;
        result.imag=this->imag+other.imag;
        return result;
    }
    friend ostream& operator<<(ostream& os, const Complex& c)
    {
        os << c.real << "+i" << c.imag;
        return os;
    }
    

    };

    int main() { Complex x,y; Complex result; x.input(); y.input(); result=x+y; cout<

  • + 0 comments

    Here is Overload Operators solution in c++ - https://programmingoneonone.com/hackerrank-overload-operators-solution-in-cpp.html