'recursive' overloaded operator

hi guys,

I just finished reading the tutorial and im trying to understand some object programming concepts so be slow with me :D

I have been trying to imitate some things i already see on the language.

In this case I wanted to imitate the following:

 
cout << "some text" << "more text";


so, reading around in the references i saw that
1) cout is an object
2) << is an operator function
3) that operator is overloaded

so consider this little code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <sstream>
using namespace std;

class base {
public:
	void operator < (const string text){
		cout << text << endl;
	}
}print;

int main(){
	print < "this is a test";
	cin.get();
	return 0;
}


all is nice up to now.

The problem is cant imitate the following:
 
print < "this is a test\n" < "and this is why it fails";


since i have to create an overloaded operator that handles this case.
But how can i do that?

I have been reading this:
http://cplusplus.com/reference/iostream/ostream/operator%3C%3C/

and the closest that i can think that does that is:
ostream& operator<< (ostream& ( *pf )(ostream&));
ostream& operator<< (ios& ( *pf )(ios&));
ostream& operator<< (ios_base& ( *pf )(ios_base&));


But i dont quite get it, and havent been able to make it work.
Any help would be appreciated.
You can repeat the << because it returns an ostream&.
type of cout is ostream, so you can write cout << "str"
type of (cout << "str") is also ostream (reference), since operator << returns that.
therefore you can write cout << "a" << "b";
Thank you very much.

basically this solved it:

1
2
3
4
5
6
7
8
9
public:
	base& operator < (const string text){
		cout << text << endl;
		return *this;
	}
	base& operator < (base* text){
		cout << text << endl;
		return *this;
	}


So the operator function returns "*this" (which i read as the info stored in the pointer of the currently executing object) and accepts it as well, so i can call it over and over like this:

1
2
3
4
5
6
int main(){
	print < "this is a test" < "and this too"
		< "and this" < "and this as well";
	cin.get();
	return 0;
}
Just out of interest - why are you using < instead of <<

I know there is actually no law against the way you have done it - but << and >> have become associated in C++ programmers minds with stream insertion/extraction operations (as well as the usual left shift and right shift).

Last edited on
No reason in particular.

at the beginning I was going to use ',' (comma) for the operation since i have some experience with autohotkey, a cool scripting language, and in there you would do something like:

1
2
3
4
5
msgbox, some text

// or

msgbox, 64, the title of the msgbox goes here, the text of it goes here


I decided not to so i dont go back to old habits... you know, im like learning from 0.
Topic archived. No new replies allowed.