Can anybody tell me how to overload << operator ?

Recommended Answers

All 3 Replies

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.

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;
}

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';
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.