Operator overloading

Here's an attempt at overloading the << operator for a new class for complex numbers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <cmath>
using namespace std;

class Complex
{
private:
    int real,imag;
public:
    Complex(int a,int b)
    {
        real = a;
        imag = b;
    }
    Complex(){real = imag = 0;}
    double re()
    {
        return real;
    }
    double im()
    {
        return imag;
    }
    friend ostream& operator << (ostream& out,Complex no);
};

ostream& operator << (ostream& out,Complex no)
{
    out << no.re() << " + " << no.im() << "i";
    return out;
}

int main()
{
    cout << new Complex(0,1) << endl;
}


The expected result is 0 + 1i. I'm getting 0x107100a30. I'm sure there's some error, but where?
That is because you are outputting the pointer returned by new. It needs dereferenced before sending it out the stream.

Try:
1
2
3
4
5
6
int main()
{
    Complex n(0,1);
    cout << n << endl;
    return 0;
}


Or, if you do want the object created dynamically:
1
2
3
4
5
6
7
int main()
{
    Complex * ptr = new Complex(0,1);
    cout << (*ptr) << endl;
    delete ptr;
    return 0;
}


By the way, operator<< does not have to be a friend since it is only using Complex's public API.

Also, the Complex argument to operator<< can be const Complex &.

(And I assume you are already aware that there is a std::complex type)
Last edited on
Ah. That always gets me. I seem to assume the C++ new keyword acts effectively identically to C#'s and Java's. Thanks, you've helped me quite a bit with operator overloading!
Topic archived. No new replies allowed.