我有一个包含对字符串流(用作整体应用程序日志)的引用的类。如何将文本添加到引用的字符串流?
一个例子(因为我不能在这里发布实际来源...)
主
stringstream appLog;
RandomClass myClass;
.....
myClass.storeLog(&applog);
myClass.addText("Hello World");
cout << appLog.str().c_str() << endl;
随机类 cpp
void RandomClass::storeLog(stringstream *appLog)
{
m_refLog = appLog;
}
void RandomClass::addText(const char text[])
{
m_refLog << text; //help here...?
}
我在使用与上述非常相似的设置和方法结构的真实应用程序中遇到以下错误。
error C2296: '<<' : illegal, left operand has type 'std::stringstream *'
error C2297: '<<' : illegal, right operand has type 'const char [11]'
我知道这个错误是因为我正在使用一个引用并仍在尝试做“<<”,但我还能怎么做呢? m_refLog-><<
???
最佳答案
先解除对指针的引用
void RandomClass::addText(const char text[])
{
if ( m_refLog != NULL )
(*m_refLog) << text;
}
在构造函数中,将成员指针初始化为NULL
RandomClass::RandomClass() : m_refLog(NULL)
{
...
}
关于c++ - operator<< 和 std::stringstream 引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5937073/