简体   繁体   English

使用ifstream时的语法错误

[英]syntax error when using ifstream

It's been a long time since I've done any C++. 自从我完成任何C ++以来已经很长时间了。 What's wrong with this code? 此代码有什么问题?

#include <iostream>
#include <fstream>

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

Gives: 得到:

$ 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");

You used a & when you should not have done. 当您不应该使用&时,便使用了&

#include <iostream>
#include <fstream>

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

Passing values by reference isn't done in the variable declaration, but instead in the parameter list of the function using the ifstream object. 通过引用传递值不是在变量声明中完成,而是在使用ifstream对象的函数的参数列表中完成。 For example, your function main might look like this: 例如,函数main可能如下所示:

#include <iostream>
#include <fstream>

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

and your called function should look like this: 并且您调用的函数应如下所示:

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

If you need the C++11 reference type (which I doubt, but maybe), try this: 如果您需要C ++ 11引用类型(我对此表示怀疑,但也许),请尝试以下操作:

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

That works in a lot of cases where doing a regular by-ref wouldn't. 在很多情况下,做常规的旁审都不可行。

semantically, a reference is a pointer. 从语义上讲,引用是指针。 so your code doesn't compile for the same reason this code doesn't: 因此您的代码不会出于以下原因而无法编译:

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

as others have said, you want to create an object of type ifstream. 正如其他人所说,您想创建一个ifstream类型的对象。 not a reference (nor a pointer) to it. 不是对它的引用(也不是指针)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM