I have a class Terminallog which is overloading the << operator. If I do the following
Terminallog clog(3);
clog <<开发者_如何学Go; "stackoverflow.com is cool" << endl;
everything works fine. "stackoverflow.com is cool" is printed in a nice colored way to the screen, exactly what Terminallog is supposed to do.
Now I try
Terminallog* clog = new Terminallog(3);
clog << "stackoverflow.com is cool" << endl;
which gives me a compiler error:
error: invalid operands of types ‘Terminallog*’ and ‘const char [5]’ to binary ‘operator<<’
I can see that it is problem passing the "<<" operator to a pointer, but how can I get the same behaviour as with the non pointer version? I could simply dereference the pointer, but that would create a local copy of the object (which is no good for performance isn't it?)
Therefore I wonder what is the correct way to do it?
Thanks in advance
ftiaronsem
Dereferencing a pointer to write
*clog << "My message" << endl;
does not create a copy of the object being pointed at. In general, pointer dereferences don't make copies, and the only way to make a copy is to either explicitly create one, pass an object into a function by value, or return an object from a function by value. The above code with the pointer dereference is probably what you're looking for.
Actually dereferencing the pointer gives you a reference, not a copy, so you're fine. (Attempting to copy a stream would and should fail, anyway; streams are not containers but flows of data.)
*clog << "text" << std::endl;
You can't write a free ("global") function operator<<
taking a pointer-to-TerminalLog
on the left and the other stuff on the right, because the language requires at least one of the operands to operator<<
to be a class or enum type, and your RHS argument often won't be one.
Dereferencing the pointer does not create a copy, it creates a reference. You can just de-ref it and get the correct behaviour, no copying.
Terminallog* clog = new Terminallog(3);
Terminallog& clog_r = *clog;
clog_r << "stackoverflow.com is cool" << endl;
Simple: (*clog) << "stackoverflow.com is cool" << endl;
This does not create a copy of clog
.
精彩评论