#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/