c++ - 子类化 stringstream 给出 "0x401bad ABC"而不是 "Foo ABC"

标签 c++ stringstream

#include <sstream>
#include <iostream>
#include <string>

class A : public std::stringstream {
        public:
                A() {}
                ~A() { std::cout << str().c_str() << std::endl; }
};

int main() {
    A() << "Foo" << std::string(" ABC");
}

我期待程序打印:

Foo ABC

代替

0x401bad ABC

为什么打印0x401bad ABC

g++ --version
g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3

最佳答案

operator<<分两部分实现:

  • 字符数据的重载是自由函数。
  • 其他重载是 std::ostream 的成员.

我们担心 first one对于那个字符串文字。正如您在链接中看到的,所有重载都采用非常量引用 std::ostream .这意味着您的临时 A()不适合。因此,member function服用const void*被使用。

C++11 添加了对 std::ostream 右值引用的支持对于通用 const T &参数,它接受您的临时对象,因此在使用 C++11 编译时会打印字符串文字。

关于c++ - 子类化 stringstream 给出 "0x401bad ABC"而不是 "Foo ABC",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28612236/

相关文章:

C++ std::stringstream >> std::string 只存储第一个条目?

c++ - 从字符串中提取字符时,基于范围的循环和stringstream有什么区别

c++ - 混合在堆上和堆栈上创建的 vector 对象

c++ - 为什么我需要 FreeGLUT 来编译和链接一个 GLFW 程序

c++ - stringstream:为什么这段代码不返回 4?

c++ - std::stringstream 和 str 方法

c++ - 为什么 stringstreams rdbuf() 和 str() 给我不同的输出?

java - 如何在 Java 中将有符号 16 位整数转换为无符号 16 位整数?

c++ - 无法在不破坏堆叠顺序的情况下使 QQuickWidget 背景透明

c++ - void abort() 的声明抛出不同的异常