Hi all,

I am trying to create a class to serve as a customized cout class. Right now I have made some test code to see if I can do it. Right now I am trying to make it function just like cout, but later I will have it do more than just print text to the screen.

Currently my class works when I try and print one item, but not multiple ones.


The code:

#include "operator.h"

using namespace std;

void printclass::operator<<( const string & mesg )
{
    cout << mesg;
}

int main()
{
    printclass print;

    print << "hi"; print << "\n"; //this complies
    
    print << "hi" << "\n"; //but this doesn't

    return 0;
}
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

class printclass
{
    public:
    void operator<<( const string & mesg );
};

The problem is that print << "hi" << "\n"; will not compile. This does not surprise me, but I do not know how to modify my class to make it work. Anyone have any suggestions?

Thanks in advance.

Two suggestions:

1) you should make your operator overload a free-function (or friend) not a member function (this can be important for argument-dependent lookup of the correct overload).

2) to chain the operators, you need to return a reference to the printclass object from your operator.

With that, you should have:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

class printclass
{
  public:
    friend
    printclass& operator<<( printclass& out, const string & mesg );
};


printclass& operator<<( printclass& out, const string & mesg )
{
    cout << mesg;
    return out;
}
This question has already been answered. Start a new discussion instead.