将字符串写入 ostream

5

当我尝试在Qt 4.8中使用llvm-g++-4.2 (GCC) 4.2.1编译下面的代码时,会出现以下错误:

../GLWidget.cpp:24:   instantiated from here
../GLWidget.cpp:24: error: explicit instantiation of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&, const std::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]' but no definition available 

这个错误是什么意思?我该怎么修复它呢?

源代码:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

void testOStream(){
    filebuf fb;
    fb.open ("test.txt",ios::out);
    std::ostream os(&fb);
    std::string test("test");
    os << test; // This line has the problem
    fb.close();
}

可以在ideone上编译成功。 - Tom Knapen
1
这个应该可以编译通过,但是尝试添加 #include <ostream> - user93353
2
如果你使用的是Mac OS X Mountain Lion,那么这似乎是一个常见的问题,尝试将-mmacosx-version-min=10.7添加为编译标志。 - Chad Campbell
1
有趣的是,在C++11之前,iostream不需要包含#include <ostream> - Sebastian Mach
错误出现在 os << test; 这一行,并且抱怨 std::operator<< 函数。 - aschepler
显示剩余5条评论
3个回答

3
如果您使用的是C++11之前的版本,您可能需要将#include <ostream>添加到您的程序中。
仅在C++11及更高版本中需要<iostream>#include <ostream>
头文件<iostream>概要。
namespace std {
   extern istream cin;
   extern ostream cout;
   extern ostream cerr;
   extern ostream clog;

   extern wistream wcin;
   extern wostream wcout;
   extern wostream wcerr;
   extern wostream wclog;

}

C++2011:

#include <ios>
#include <streambuf>
#include <istream>
#include <ostream>

namespace std {
    extern istream cin;
    extern ostream cout;
    extern ostream cerr;
    extern ostream clog;

    extern wistream wcin;
    extern wostream wcout;
    extern wostream wcerr;
    extern wostream wclog;
}

0
请确保您的代码中包含 #include <ostream>。在 C++11 之前,<iostream> 并不保证会包含 <ostream>。定义 os 可能是正确的原因是因为通常实现定义了哪些标准库头文件包含其他标准库头文件(除非另有规定)。在您的实现中,<iostream> 可能已经包含了 std::ostream 的定义,但没有与之相关的函数。然而,如果您正在编译 C++11,则应该已经包含了所有内容。

但是必须包含 <ostream> 才能使用 <iostream> - aschepler
是的,我检查了一个标准,没有意识到它被更改了。 - aschepler

0
正如@ChadCambell所指出的那样,问题实际上是Qt 4.8使用了-mmacosx-version-min=10.5,但应该是-mmacosx-version-min=10.7。
我在这里找到了更多关于这个问题的有用信息:

http://qt-project.org/forums/viewthread/19106/P15

升级到Qt 5.0也可以解决这个问题


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接