$ uname -a
Darwin Wheelie-Cyberman 10.8.0 Darwin Kernel Version 10.8.0: Tue Jun 7 16:33:36 PDT 2011; root:xnu-1504.15.3~1/RELEASE_I386 i386
$ g++ --version
i686-apple-darwin10-g++-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5666) (dot 3)
Copyright (C) 2007 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ cat nolove.cc
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char ** argv) {
unsigned long long i = 0;
ostringstream o();
// Compiles fine
cout << i;
// Explodes, see below
o << i;
return 0;
}
$ g++ -o nolove nolove.cc
nolove.cc: In function ‘int main(int, char**)’:
nolove.cc:14: error: invalid operands of types ‘std::ostringstream ()()’ and ‘long long unsigned int’ to binary ‘operator<<’
我对 C++ 有点陌生(但对编程或面向对象设计等不熟悉),所以我假设我只是做错了。实际上,上面的 unsigned long long 相当于我的目标平台上的无符号 64 位整数(上面和 linux 2.6 上的 g++ 4.4.1),相当于相同事物的不同类型也是可以接受的(但我还没有找到任何.)
我可以使用 ostringstream 来格式化此(或类似)类型吗?如果没有,我可以在不拖入 stdio 和 snprintf 的情况下完成吗?从更哲学的角度来说,cout 可以执行的类型是如何实现的,以及为什么没有将该功能扩展到字符串流内容?
最佳答案
这是因为这个
ostringstream o();
不声明变量,而是声明返回流的函数。
试试这个
ostringstream o;
另请参阅
关于c++ - ostringstream 运算符<< 很长吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7226769/