ostringstream运算符<<好久不过?

时间:2011-08-29 06:17:35

标签: c++ long-integer cout ostringstream

$ 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 ++有些新手(但不是编程或OO设计等),所以我假设我做错了。实际上,unsigned long long在我的目标平台上等同于一个无符号的64位整数(上面和linux 2.6上的g ++ 4.4.1),一个不同的类型相同的东西也是可以接受的(但是我还没有找到) 。)

我可以使用ostringstream格式化此(或类似)类型吗?如果没有,我可以不拖入stdio和snprintf吗?更哲学的是,打字是如何解决cout可以做到的,为什么这个功能没有扩展到字符串流的东西?

1 个答案:

答案 0 :(得分:6)

这是因为这个

ostringstream o(); 

不声明变量,而是声明返回流的函数。

试试这个

ostringstream o; 

另见

Most vexing parse: why doesn't A a(()); work?