[英]Why can't I initialize an ifstream in the initializer list of the constructor of a class?
#include <fstream>
#include <iostream>
using namespace std;
class file_reader {
public:
file_reader(const char* file_name) : file(ifstream(file_name)) { }
char operator[](int index) const {
file.seekg(index);
return file.get();
}
private:
ifstream file;
};
I get an error: 'std::ios_base::ios_base(const std::ios_base&)' is private
. 我收到一个错误:
'std::ios_base::ios_base(const std::ios_base&)' is private
。 Seems like the code is trying to call a constructor higher in the hierarchy. 似乎代码正在尝试调用层次结构中更高的构造函数。 Although
ifstream
has a constructor that takes a const char*
. 尽管
ifstream
有一个采用const char*
的构造const char*
。 What's the problem? 有什么问题?
By creating a temporary ifstream(file_name)
then initialising file
from it, you're trying to invoke file's copy constructor, and this fails because that constructor is private where it is declared (in the base ios_base
); 通过创建一个临时的
ifstream(file_name)
然后从中初始化file
,您试图调用文件的复制构造函数,但是失败了,因为该构造函数在声明它的位置是私有的(在ios_base
); streams cannot be copied. 流无法复制。
I'm sure you meant to write this: 我确定你打算写这个:
file_reader(const char* file_name) : file(file_name) { }
Remember, this: 记住这一点:
struct T
{
S object;
type() : object(arg) {};
};
in terms of initialising a S
is much like: 在初始化
S
方面很像:
int main()
{
S object(arg);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.