I am trying to understand how operator overloads works.
I want to code it so that I can write
Log(Log::LEVEL_ERR) << "fatal error: " << 13 ;
And for both the string and the number the overloaded operator is used.
I now have
class Log{
public:
std::ostream& operator<<(char const*);
}
std::ostream& Log::operator<<(char const* text){
if (Log::isToWrite()) {
printLevel();
std::cout << text;
}
return std::cout;
}
This only get’s me the string but not the number, why?
Edit
@bitmask Just to be clear, you mean implement like this:
class Log{
public:
friend Log& operator<<(Log& in, char const* text);
}
friend Log& operator<<(Log& in, char const* text){
if (in.isToWrite()) {
in.printLevel();
std::cout << text;
}
return std::cout;
}
Because I get these everywhere now:
error: Semantic Issue: Invalid operands to binary expression (‘Log’ and ‘const char [15]’)
Maybe this is really simple but can you spell it out for me?
I’m really not getting it.
Because you returned an
ostream&, the next<<operator matchesoperator<<(ostream&, int). You shouldreturn *this;(type isLog&) instead, so that the next<<operator matches an operator defined for your class.