gpt4 book ai didi

c++ - ostringstream operator<< 长时间?

转载 作者:搜寻专家 更新时间:2023-10-31 00:19:55 26 4
gpt4 key购买 nike

$ 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 可以执行的类型是如何完成的,为什么不将该功能扩展到字符串流的内容?

最佳答案

这是因为这个

ostringstream o(); 

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

试试这个

ostringstream o; 

另见

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

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com