Knowee
Questions
Features
Study Tools

Write a program overloading arithmetic operators to add two complex numbers using oops c++

Question

Write a program overloading arithmetic operators to add two complex numbers using OOPS C++

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a simple C++ program that overloads arithmetic operators to add two complex numbers:

#include<iostream>
using namespace std;

class Complex {
private:
    int real, imag;
public:
    Complex(int r = 0, int i =0)  {real = r;   imag = i;}

    // This is automatically called when '+' is used with
    // between two Complex objects
    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 << endl; }
};

int main()
{
    Complex c1(10, 5), c2(2, 4);
    Complex c3 = c1 + c2; // An example call to "operator+"
    c3.print();
}

In this program, we define a class Complex to represent complex numbers. We then overload the + operator to add two Complex objects. The operator+ function takes a Complex object as an argument and adds the real and imaginary parts of the caller object to the real and imaginary parts of the argument object. The result is returned as a new Complex object.

This problem has been solved

Similar Questions

Write a program to overload arithmetic minus operator for subtracting two complex numbers (use constructors also).

C Program to Calculate Multiplication and Addition, and Check Division Remainder

Write a program to enter two numbers and print the arithmeticoperations like +,-,*,**, /, // and % using function

Which of the following special methods is used for overloading the addition operator? __add____plus____sum____addition__

The output of the code will be ____. int i=5; printf(“%d %d %d”, i, i++, ++i); ans. 7 6 5 7 6 6 5 5 7 7 6 7

1/1

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.