Can't find an applicable example for this form of operator << overloading

Instead of the normal example:
ostream& operator << (ostream& os, class &x)
I am attempting something more along these lines:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
#include <cstdio>
#include <unistd.h>
using namespace std;

class Socket
  {
  public
  Socket( void );
  ~Socket( void );

  bool flush( void );

  Socket* operator<< ( int value );
  Socket* operator << ( char *value );

  protected:
  int descriptor;
  string buffer;
};


...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Socket* Socket::operator << ( int value ) {
char number_string[25];

snprintf( number_string, 25, "%d", value );
buffer += (string) number_string;
return this;
}

Socket* Socket::operator << ( char *value ) {
buffer += (string) value;
return this;
}

bool Socket::flush( void ) {
if (write( descriptor, buffer.c_str(), buffer.length() ) <= 0)
  return false;
buffer.clear();
return true;
}


The code compiles, but when using something like:
1
2
3
4
5
int main( void ) {
Socket *socket = new Socket;
int number = 32;
socket << number;
return 0; }


I receive the following error:
error: invalid operands of types 'Socket*' and 'int' to binary 'operator<<'

I know my functions don't necessarily need to return pointers to the Socket class, but I wouldn't think this would be part of the problem. I also don't see how using the original example of overloading ostream would help, but I can't find an example of this in the archives.
overloaded operators work on OBJECTS, not on pointers. You'd need to do the following:

1
2
// socket << number;  // <- no good, 'socket' is a pointer, not an object
*socket << number;  // <- good, '*sockect' is an object 


What's more, in order to make this properly stackable, you need to return a reference, not a pointer:

1
2
3
4
5
6
7
8
9
10
11
//  BAD
Socket* Socket::operator << ( char *value ) {  // Socket*, char*
buffer += (string) value;
return this;  // returning a pointer
}

// GOOD
Socket& Socket::operator << ( const char *value ) { // Socket&, const char*
buffer += (string) value;
return *this;  // returning a reference
}

I appreciate your help. I really should have caught the first issue, but wasn't aware of the second.

I can't thank you enough for the feedback!
Topic archived. No new replies allowed.