Overload << C ++ operator - a pointer to a class

 class logger { .... }; logger& operator<<(logger& log, const std::string& str) { cout << "My Log: " << str << endl; return log; } logger log; log << "Lexicon Starting"; 

Works well, but instead, I would like to use a pointer to an instance of the class. i.e.

 logger * log = new log(); log << "Lexicon Starting"; 

Is it possible? If so, what is the syntax? Thanks

Edit: Compiler Error

 error: invalid operands of types 'logger*' and 'const char [17]' to binary 'operator<<' 
+3
source share
5 answers

You will need to dereference the pointer to your log object and obviously check if it is 0. Something like this should do the job:

 log && ((*log) << "Lexicon starting") 

In general, I would shy away from referencing objects like a journal (which you usually unconditionally expect to be present) with a pointer due to the uncertainty you get with a pointer, is there an AKA or not?

+11
source

Like this:

 logger * log = new log(); (*log) << "Lexicon Starting"; 
+9
source

Why not use the link?

 logger & log = *(new log()); // the above is abhorrent code that // should be replaced by something meaningful log << "Lexicon Starting"; 

If this is not what you want, I would go with Timo Geusch , even if it is ugly

+5
source

Depending on the context from which you get your registrar, you may want to return a link instead of a pointer:

 ... Logger& logger() { return *_pLogger; } ... Logger& log = logger(); log << "..."; 
+2
source

Not really. new log( ) is of type pointer, "Lexicon starting" is of type const char[16] . You can only overload operators if at least one argument is of a user-defined type.

decasteljau correctly noted that you can do this via (*log) if you want a pointer. However, I do not like the pointer. Andrei Alexandrescu devotes a lot of pages to smart loggers in "Modern C ++ Design", perhaps you should consult with this.

+2
source

All Articles