首页 > 解决方案 > 非法操作stringstream << stringstream与c ++ 11

问题描述

我正在尝试使用developerstudio12.6 在solaris11 上使用-std=c++11 编译现有的cpp 代码,但出现非法操作错误。使用 -std=c++03 编译很好。

任何帮助将不胜感激。这是简化的代码:

一个.cpp:

#include <sstream>
#include <string>

int main()
{
   std::stringstream traceTabName;
   std::stringstream tabName1;

   tabName1 << "hello";
   traceTabName << tabName1;
}

“a.cpp”,第 10 行:错误:操作“std::stringstream << std::stringstream”是非法的。

标签: c++

解决方案


没有可以将一个输出到另一个的<<运算符。std::stringstream但是,有一个<<可以输出const void *指针的运算符。

在 C++03 std::stringstream(或更准确地说,它的基类std::basic_ios)中,可以隐式转换为void *. 这就是 C++03 模式下发生的事情

traceTabName << tabName1;

它被解释为

traceTabName << (void *) tabName1;

从 C++11 开始,这种隐式转换不再可用,这就是代码不再编译的原因。此转换已替换为转换为bool,更重要的是,它现在被声明为explicit.

在 C++03 中它是“可编译的”,但它并没有做你可能期望它做的事情。在任何版本的语言规范中实现你的意图(如我所见)你必须做

traceTabName << tabName1.str();

推荐阅读