[英]operator<< and std::stringstream reference?
I have a class that holds a reference to a stringstream (used as an overall application log). 我有一个类,它包含对stringstream的引用(用作整个应用程序日志)。 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 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-><<
??? 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 在构造函数中,使用NULL将成员指针初始化为stringstream
RandomClass::RandomClass() : m_refLog(NULL)
{
...
}
看起来你的m_refLog
成员是一个StringStream *
(即一个指向StringStream
的指针),而不是一个StringStream
(或一个StringStream &
。这就是你的编译错误的来源。
You have a pointer, not a reference. 你有一个指针,而不是一个参考。 Dereference it to obtain the stream itself. 取消引用它以获取流本身。
(Recall that ptr->foo()
is equivalent to (*ptr).foo()
.) (回想一下, ptr->foo()
相当于(*ptr).foo()
。)
I'd also recommend that your functions accept const std::string&
instead of pointers to C-style char
buffers. 我还建议你的函数接受const std::string&
而不是指向C风格char
缓冲区的指针。
And the .c_str()
in your example is redundant. 你的例子中的.c_str()
是多余的。
void RandomClass::addText(const std::string& text) {
(*m_refLog) << text;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.