2013-01-24 184 views
0

我今天剛遇到一個問題:下面的代碼似乎在MSVC++ 2010中工作,但不能與Clang LLVM 4.1(使用GNU ++ 11)一起工作。在C++中傳遞fstream參數作爲函數參數11

#include <fstream> 

void foo(std::fstream& file){ 
    file << "foo"; 
} 
int main() { 
    std::fstream dummy("dummy"); 
    foo(dummy); 
    return 0; 
} 

生成

Invalid operands to binary expression (std::fstream (aka basic_fstream<char>) and const char[4]) 
上鏘

。我認爲通過引用傳遞iostream參數將是C++中的常見做法。我甚至不確定這是否與叮噹聲,C++ 11或其他任何東西有關。

任何想法如何將流傳遞給函數呢?

+2

該代碼是正確的。 [檢查它在這裏](http://liveworkspace.org/code/2bhYJa$2)自己與鏗鏘語+ 3.2。 – Ali

+3

你是否缺少'#include '?如果不是,請發佈完整的[SSCCE](http://sscce.org/)。 – ildjarn

+4

你可以'#include '它允許你使用指針和引用,但是不能真正使用這些對象。另外,對於流,請傳遞基類。另一個問題:這是打算寫成流嗎?如果是,則使用'std :: ostream&out'作爲參數。如果它也應該被讀取,那麼使用'std :: iostream&stream'。只有當您需要特定於文件流的內容時,才使用代碼中的表單。 –

回答

3

我認爲你原來的代碼(即只部分地張貼在你原來的問題)看起來是這樣的:

#include <iosfwd> 

void foo(std::fstream& file){ 
    file << "foo"; 
} 

int main() { 
    std::fstream dummy("dummy"); 
    foo(dummy); 
    return 0; 
} 

事實上,這提供了以下錯誤消息鐺++ 3.2

Compilation finished with errors: 
source.cpp:4:10: error: invalid operands to binary expression ('std::fstream' (aka 'basic_fstream<char>') and 'const char [4]') 
file << "foo"; 
~~~~^~~~~~ 
source.cpp:8:17: error: implicit instantiation of undefined template 'std::basic_fstream<char, std::char_traits<char> >' 
std::fstream dummy("dummy"); 
^ 
/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../../include/c++/4.7/iosfwd:118:11: note: template is declared here 
class basic_fstream; 
^ 
2 errors generated. 

不幸的是,你只發布了第一條錯誤消息,而不是第二條。

從第二個錯誤消息,很明顯你只有#include <iosfwd>而不是#include <fstream>。如果你解決這個問題,一切都會好的。

下次請發佈完整的代碼和所有的錯誤消息。