Search
 
SCRIPT & CODE EXAMPLE
 

CPP

how to do (binary) operator overloading in c++

// C++ program to overload the binary operator +
// This program adds two complex numbers

#include <iostream>
using namespace std;

class Complex {
   private:
    float real;
    float imag;

   public:
    // Constructor to initialize real and imag to 0
    Complex() : real(0), imag(0) {}

    void input() {
        cout << "Enter real and imaginary parts respectively: ";
        cin >> real;
        cin >> imag;
    }

    // Overload the + operator
    Complex operator + (const Complex& obj) {
        Complex temp;
        temp.real = real + obj.real;
        temp.imag = imag + obj.imag;
        return temp;
    }

    void output() {
        if (imag < 0)
            cout << "Output Complex number: " << real << imag << "i";
        else
            cout << "Output Complex number: " << real << "+" << imag << "i";
    }
};

int main() {
    Complex complex1, complex2, result;

    cout << "Enter first complex number:
";
    complex1.input();

    cout << "Enter second complex number:
";
    complex2.input();

   // complex1 calls the operator function
   // complex2 is passed as an argument to the function
    result = complex1 + complex2;
    result.output();

    return 0;
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: c++ get time 
Cpp :: remove last character from string c++ 
Cpp :: return by reference in cpp 
Cpp :: c++ loop through string 
Cpp :: wine linux 
Cpp :: how to open and read text files in c++ 
Cpp :: adding elements to a vector c++ 
Cpp :: c++ program to find prime number using function 
Cpp :: C++ switch cases 
Cpp :: array and for loop in c++ 
Cpp :: iterating in map/unordered map c++ 
Cpp :: c++ vector average 
Cpp :: c++ return multiple values 
Cpp :: sleep system function linux c++ 
Cpp :: c++ terminal color 
Cpp :: nth node from end of linked list 
Cpp :: cpp init multidimensional vector 
Cpp :: c++ enum 
Cpp :: How to find the suarray with maximum sum using divide and conquer 
Cpp :: how to add an element to std::map 
Cpp :: ViewController import 
Cpp :: check if a string is palindrome cpp 
Cpp :: C++ String Length Example 
Cpp :: what is c++ standard library 
Cpp :: concat two vectors c++ 
Cpp :: c++ int to char* 
Cpp :: c++ average 
Cpp :: stl vector 
Cpp :: how to delete a node c++ 
Cpp :: convert characters to lowercase c++ 
ADD CONTENT
Topic
Content
Source link
Name
9+2 =