Overloading operator

Hi, I understand how to overload the << to display a class instance. For example cout << Ins << endl;. How would you cout two instance like ? cout << Ins1 + Ins2
Thanks in advance
std::cout << Inst1 << Inst2 << std::endl;

Have you not tried that?

EDIT:
Wait, do you want to be able to use the addition operator to output two objects?
Last edited on
I have to do it like cout << Ins1 + Ins2 << endl;
Is it possibly to overload the addition operator to output two object? I have already overloaded << to print one instance like cout << Ins << endl;
Do you mean something like this?
You would have to overload the +operator.

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
37
38
39
class Foo
{
    public:
        Foo(int n = 0):
            num(n) { }
        friend std::ostream &operator<<(std::ostream&, const Foo&);

        Foo &operator+=(const Foo&);
        friend Foo operator+(const Foo&, const Foo&);
    private:
        int num;
};

std::ostream &operator<<(std::ostream &out, const Foo&s)
{
    out << s.num;
}

Foo &Foo::operator+=(const Foo &rhs)
{
    num += rhs.num;
    return *this;
}

Foo operator+(const Foo &lhs, const Foo &rhs)
{
    Foo ret(lhs);
    ret += rhs;
    return ret;
}

int main()
{
    Foo obj1(5);
    Foo obj2(10);
    Foo obj3(15);
    std::cout << obj1 + obj2 + obj3 << std::endl;
    return 0;
}


edit: Changed the code a bit
Last edited on
@gemic I understand what you did but if you were to created a 3rd Foo obj3
how would the Foo &operator+(const Foo&) be able to add just the Foo obj2 + Foo obj3 inside int main()
Foo obj1, obj2, obj3;


obj1 + obj2 + obj3;

is equivalent to

( obj1.operator +( obj2 ) ).operator +( obj3 );


However it is better to define operator + as a non-member function because the definition above has incorrect semantic. It is equivalent to the operator += instead of operator +
Last edited on
Thanks Guys I understand I will post the finish code later

However it is better to define operator + as a non-member function because the definition above has incorrect semantic. It is equivalent to the operator += instead of operator +


Yes it was a mistake on my part :P
I have rewritten the code. It should do the right thing now.
As for me I would declare it for this concrete class as

const Foo operator+(const Foo &lhs, const Foo &rhs);

because I do not see a sense in the construction


Foo obj1, obj2, obj3;

( obj1 + obj2 ) = obj3;
Topic archived. No new replies allowed.