【发布时间】:2011-11-05 01:42:52
【问题描述】:
如果不将文件存储在变量中,我似乎无法打开文件。我可以这样做:
ifstream blob("somefile");
string line;
blob >> line;
但是当我尝试这个时:
string line;
ifstream("somefile") >> line;
编译器(clang)给出这个错误:
t.cpp:7:23: error: invalid operands to binary expression ('ifstream' (aka 'basic_ifstream<char>') and 'string' (aka 'basic_string<char>'))
ifstream("thing") >> i;
~~~~~~~~~~~~~~~~~ ^ ~
In file included from t.cpp:1:
In file included from /usr/include/c++/4.6/iostream:39:
In file included from /usr/include/c++/4.6/ostream:39:
In file included from /usr/include/c++/4.6/ios:42:
In file included from /usr/include/c++/4.6/bits/ios_base.h:42:
In file included from /usr/include/c++/4.6/bits/locale_classes.h:41:
In file included from /usr/include/c++/4.6/string:53:
/usr/include/c++/4.6/bits/basic_string.h:2679:5: note: candidate function [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>] not
viable: no known conversion from 'ifstream' (aka 'basic_ifstream<char>') to 'basic_istream<char> &' for 1st argument
operator>>(basic_istream<char>& __is, basic_string<char>& __str);
^
In file included from t.cpp:1:
In file included from /usr/include/c++/4.6/iostream:40:
/ usr/include/c++/4.6/istream:121:7: note: candidate function not viable: no known conversion from 'string' (aka 'basic_string<char>') to
'__istream_type &(*)(__istream_type &)' for 1st argument
operator>>(__istream_type& (*__pf)(__istream_type&))
^
/usr/include/c++/4.6/istream:125:7: note: candidate function not viable: no known conversion
... a few more hundred pages of crap ...
1 error generated.
那么,这两者有什么区别呢?对于其他类,直接调用它就可以了。是否涉及一些模板魔法使其模棱两可?
【问题讨论】:
-
@Kerrek:你为什么要删除它?!
-
@KerrekSB 我同意 Tomalak 的观点,看起来像是我的答案。
-
奇怪的是,(或者也许不是那么奇怪),这在 VC10 中运行良好。也许这就是Kerrek删除他的答案的原因。在这种情况下,VC10 不兼容。
-
@BenjaminLindley:事实上,Visual C++ 是兼容的。
operator>>重载的规范在 C++11 中发生了变化。 -
我原来的错误信息实际上是完全不相关的(缺少头文件)。我现在已经粘贴了正确的错误消息。