c++ - operator<< 和 std::stringstream 引用?

标签 c++ std stringstream

我有一个包含对字符串流(用作整体应用程序日志)的引用的类。如何将文本添加到引用的字符串流?

一个例子(因为我不能在这里发布实际来源...)

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/

相关文章:

c++ - OfxEtherDream : where is getNumEtherdream()?

c++ - SDL_Image 不显示图像

c++ - 如何在 vector 的前面添加结构?

c++ - 使用 stringstream 将整数分配给 char 指针

c++ - stringstream 在无符号类型中失败 "streaming"负值?

c++ - 检查 std::thread 是否仍在运行

c++ - 大输入程序耗时过长

c++ - 如何检查 std 字符串中的位置是否存在? (c++)

c++ - 如何将 char[] 转换为字符串

c++ - 如何从字符串流中的同一位置读取两次?