<< operator and std :: stringstream reference?

I have a class that contains a link to a string stream (used as a general application log). How to add text to a reference stringstream?

Example (because I can not publish the real source here ...)
The main

stringstream appLog;
RandomClass myClass;
.....
myClass.storeLog(&applog);
myClass.addText("Hello World");
cout << appLog.str().c_str() << endl;

RandomClass cpp

void RandomClass::storeLog(stringstream *appLog)
{
  m_refLog = appLog;
}

void RandomClass::addText(const char text[])
{
  m_refLog << text;    //help here...?
}

I get the following error in my real application using a very similar structure of settings and methods, as mentioned above. error C2296: '<<' : illegal, left operand has type 'std::stringstream *'
error C2297: '<<' : illegal, right operand has type 'const char [11]'

I know that the error is due to the fact that I am using the link and still trying to do "<<", but how do I do this? m_refLog-><<???

+3
source share
3 answers

Remove pointer first

void RandomClass::addText(const char text[])
{
    if ( m_refLog != NULL )
        (*m_refLog) << text;    
}

stringstream NULL

RandomClass::RandomClass() : m_refLog(NULL) 
{
...
}
+7

, m_refLog StringStream * (.. StringStream), StringStream ( a StringStream &). .

+2

You have a pointer, not a link. Disassemble it to get the stream itself.

(Recall that is ptr->foo()equivalent (*ptr).foo().)

I also recommend that your functions accept const std::string&instead of pointers to charC-style buffers .

And .c_str()in your example is redundant.

void RandomClass::addText(const std::string& text) {
  (*m_refLog) << text;
}
+2
source

All Articles