$ 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等于我目标平台上的unsigned 64bit整数(在linux 2.6上为above和g++ 4.4.1),相当于同一件事的另一种类型也可以接受(但我没有找到任何类型) )

我可以使用ostringstream格式化这种(或类似的)类型吗?如果没有,我可以不拖入stdio和snprintf来做吗?从哲学上讲,键入如何计算出cout可以做到的,为什么该功能没有扩展到字符串流呢?

最佳答案

这是因为

ostringstream o();

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

试试这个
ostringstream o;

也可以看看

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

关于c++ - ostringstream运算符<<很长时间?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7226769/

10-10 08:07