4
Contributors
3
Replies
4
Views
9 Years
Discussion Span
Last Post by Tom Gunn
0

10 seconds with google finds this

But, I would not put the << endl in the overload - that limits how you can use it in building up outputs from multiple object.

0

in order to be able to overload an operator<<,it must be declared as the friend of the class.
here is the overloarding syntax:
//declaring as the class friend
friend std::ostream operator<<(std::ostream &output,classname out);
//overloading it outside the class
std::ostream operator<<(std::ostream & output,classname out)
{
//function specification here
//if you want to display the word do as for example
output<<"do";
return output;
}

0

in order to be able to overload an operator<<,it must be declared as the friend of the class.

Only if the overloaded operator needs access to the private or protected members of the class. If you only touch the public interface, the operator does not need to be a friend:

#include <iostream>

using namespace std;

namespace Daniweb
{
    class Test
    {
        int _x;
    public:
        Test(int x): _x(x) {}
        int operator()() const { return _x; }
    };

    ostream& operator<<(ostream& os, const Test t)
    {
        return os << t();
    }
}

int main()
{
    cout << Daniweb::Test(15) << '\n';
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.