Skip to main content
gamedev.net
🔒 Locked

Problem with C++ operators

Started by MartinOlsen Aug 26, 2006 at 6:09 PM 1 replies 350+ views
Original Post
MartinOlsen
MartinOlsen
Hi all. I am trying to create a logger for my game engine but have some problems with it. Consider the following code:

class CLogger {
void operator <<(std::string s) {
cout << "Logging this: " << s << endl;
}
};

int main(void) {
CLogger log;
log << "Something to log";
}

This is all dandy and good, but if I change the line with "Something to log" to something like this: log << "Something " << "to log"; I get an error, "error: void value not ignored as it ought to be", on that line! How can I make my logger accept multiple strings? (And other types like doubles, and ints?) P.S. Google wasnt too helpfull! Does someone know how, if possible, to search for special characters with Google? (Like the "<"s in c++ "operator <<")
mikeman
mikeman
The "<<" operator acts upon CLogger objects. log << "Something to log" returns void, so in what object exactly will the next operator act? If you're going to accumulate "<<" operations one after another like std::cout does, you shouldn't return void. You should return a reference to the Logger. Like this:

class CLogger {public:CLogger& operator <<(std::string s){std::cout << "Logging this: " << s << std::endl;return *this;}};int main(void) {CLogger log;log <<"Something to log"<<"Something else to log";}
MartinOlsen
MartinOlsen
Quote:
Original post by mikeman
The "<<" operator acts upon CLogger objects. log << "Something to log" returns void, so in what object exactly will the next operator act? If you're going to accumulate "<<" operations one after another like std::cout does, you shouldn't return void. You should return a reference to the Logger. Like this:

*** Source Snippet Removed ***


Thanks alot, mikeman. That did the trick!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.