开发者

operator<< and std::stringstream reference?

I have a class that holds a refer开发者_StackOverflowence to a stringstream (used as an overall application log). How do I add text to the referenced stringstream?

An example (as I cannot post actual source here...)

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'm getting the following error in my real app using a very similar setup and method structure as above. error C2296: '<<' : illegal, left operand has type 'std::stringstream *'

error C2297: '<<' : illegal, right operand has type 'const char [11]'

I know the error is because i'm using a reference and still trying to do '<<', but how else am I to do it? m_refLog-><<???


De-reference the pointer first

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

In the constructor, initialize the member pointer to stringstream with NULL

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


It looks like your m_refLog member is a StringStream * (i.e. a pointer-to-StringStream), not a StringStream (or a StringStream &. That is the source of your compile errors.


You have a pointer, not a reference. Dereference it to obtain the stream itself.

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

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

And the .c_str() in your example is redundant.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜