Overloading << operator with straming.h inside my class. Stymied.

Hi there, not sure if this is an Arduino specific thing or just C++, but I thought I'd ask here in case.

I'm trying to learn how to overload the << operator so if I create a class (say called fred) I can then say:

Serial << fred << endl

rather than:

Serial << fred.get() << endl

I've Googled like crazy and tried the non-arduino examples with no success. I expect there is a library I could use as an example. Can anyone point me in a good direction or offer help? I've also looked at Print.h and Printable.h, but I'm still learning this C++!

The base of the code I'm playing around with is below.

Thanks, Glyn

#include <streaming.h>

class StTest {
private:
	int stash ;
public:
	StTest();
	void set(int a);
	int get();

	friend Print &operator<<( Print &output, const StTest &D )
      { 
         //output << stash << endl;
         return output;            
      }

};
StTest::StTest() { stash = 0; }

void  StTest::set(int i) { stash = i; }

int StTest::get() { return stash; }

void setup()
{

  /* add setup code here */
	Serial.begin(115200);
	StTest * cl = new StTest();
	cl->set(5677);
	Serial << cl->get() << endl;
	//Serial << cl << endl;
}

void loop()
{

  /* add main program code here */

}

Wouldn't you need to overload that operator in the Serial class first?

In full fat C++ you can do it without modifying standard system files, I'm thionking the same will be possible for the arduino's flavour of C++.

I could be totally wrong though!

http://arduiniana.org/libraries/streaming/

 friend Print &operator<<( Print &output, const StTest &D )
      {
         //output << stash << endl;
         return output;           
      }

Maybe omit that? What is it doing?

You need to derive your class from printable and implement the printTo() function.

#include <Streaming.h>

class StTest : public Printable
{
  private:
    int stash;
    int count;

  public:
    StTest()
    {
      stash = 0;
      count = 0;
    };

    void set(int a)
    {
      stash = a;
      count++;
    };

    int get()
    {
      return stash;
      count--;
    };

    size_t printTo(Print& p) const
    {
      size_t n = 0;
      n += p.print(stash);
      n += p.print(' ');
      n += p.print(count);
      n += p.print(' ');
      n += p.print("whatever");
      n += p.print('\n');
      return n;
    };
};

StTest st();


void setup()
{
  Serial.begin(115200);
  Serial.println("Start ");

  st.set(42);
  Serial << st << endl;

  Serial.println("done");
}

void loop()
{
}

Or derive it from Print, and implement the write() function.

Aha! Thanks to you all. Adding Serial << *cl << endl; to setup did indeed work!

I think I was confused, oh so confused.

Now... The tricky thing now is to understand it fully!

Ta,

Glyn