使用ifstream时出现语法错误

时间:2015-05-22 19:28:45

标签: c++

自从我完成任何C ++以来,已经有很长一段时间了。这段代码有什么问题?

#include <iostream>
#include <fstream>

using namespace std;
main()
{
    ifstream& ifs("foo.txt");
}

给出:

$ g++ foo.cc 
foo.cc: In function ‘int main()’:
foo.cc:7:25: error: invalid initialization of non-const reference of type ‘std::ifstream& {aka std::basic_ifstream<char>&}’ from an rvalue of type ‘const char*’
  ifstream& ifs("foo.txt");

3 个答案:

答案 0 :(得分:3)

你不应该使用&

#include <iostream>
#include <fstream>

using namespace std;
int main()
{
    ifstream ifs("foo.txt");
}

答案 1 :(得分:1)

通过引用传递值不是在变量声明中完成的,而是在使用ifstream对象的函数的参数列表中完成。例如,您的函数main可能如下所示:

#include <iostream>
#include <fstream>

using namespace std;
int main()
{
    ifstream ifs("foo.txt");
    myFunction(ifs);
}

并且您调用的函数应如下所示:

void myFunction(std::ifstream& in_stream)
{
    // ...
}

如果你需要C ++ 11引用类型(我怀疑,但也许),试试这个:

ifstream ifs("foo.txt.");
std::ref<std::ifstream> ifs_ref(ifs);

在很多情况下,这种做法不适用于常规副编制。

答案 2 :(得分:0)

从语义上讲,引用是一个指针。所以你的代码没有编译,原因与此代码没有相同:

main()
{
  ifstream* ifs("foo.txt");
}

正如其他人所说,你想创建一个ifstream类型的对象。不是它的引用(也不是指针)。