Have a good day Mr Rohit.
The Complex sum
There is a problem at your code at two different parts of it. The first one is at your line return &temp
, the Complex object that you create at that function should be returned itself, not a reference of it. You return an object (value, as you specify at your question) in this case as a new complex is built taking the sum of two complex (the function returns a new object).
The Complex printing
By the other hand, the <<
operator overload should return a value of the type that you are specifying at that same function (an ostream &
object), which is the same that you use as the first parameter of the function. This is done for being able to concatenate more than one <<
one after each other. Of course, if you are not modifying the value of the Complex
object in that function you should name it const
. The same applies at the friend
declaration. You return a reference (ostream &
) in order to be able to concatenate more outputs later, e.g. cout << c1+c2 << "Hello world" << endl;
Bonus observations
I recommend you to modify the constructor as well as I have modified at your code below, in this case you can see assignments to member variables of the instance whose values are specified at the parenthesis after them.
By the way, if you are using friend
modifier for your functions then maybe member variables should be kept at private
section of the class, else the friend
modifier is not needed.
The Code
Your code should end like this one, which works:
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(int r = 0, int l = 0) : real(r), imagine(l) {} // Modified for simplicity purposes
friend ostream& operator<<(ostream &o, const Complex &c);
friend Complex operator+(const Complex &c1, const Complex &c2);
friend Complex operator-(const Complex &c1, const Complex &c2);
friend Complex operator*(const Complex &c1, const Complex &c2);
friend Complex operator/(const Complex &c1, const Complex &c2);
private:
int real; // Beware of using int instead of doubles when dividing
int imagine;
};
ostream& operator<<(ostream &os, const Complex &c) // If no changes are done to c, then const.
{
os << c.real << "+" << c.imagine << "i"; // It is not a good practice to add an endl here
return os;
}
Complex operator+(const Complex &c1, const Complex &c2) // No reference returned (and use const &).
{
Complex temp;
temp.real = c1.real + c2.real;
temp.imagine = c1.imagine + c2.imagine;
return temp; // No reference is returned, a new object is.
}
int main()
{
Complex c1(2,4);
Complex c2(3,2);
Complex c3 = c1 + c2;
cout << c3 << endl; // Why not using this directly if the sum is above?, endl goes here.
return 0; // This is a good practice.
}
I hope that my comments would help you to write better apps.
To know more: https://learn.microsoft.com/en-us/cpp/standard-library/overloading-the-output-operator-for-your-own-classes?view=vs-2019