简体   繁体   English

为什么不能在类的构造函数的初始化列表中初始化ifstream?

[英]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.

相关问题 为什么不能在派生类的构造函数初始化列表中初始化基类的数据成员? - Why can't Initialize the data member of base class in the constructor initializer list of derived class? 为什么我不能使用统一初始化初始化初始化列表中的引用? - Why can't I initialize a reference in an initializer list with uniform initialization? 为什么我不能使用`fstream`实例初始化对`ofstream` /`ifstream`的引用? - Why can't I initialize a reference to `ofstream` / `ifstream`, with an instance of `fstream`? 如何在varargs构造函数的初始化列表中初始化向量? - How can I initialize a vector in the initializer list of a varargs constructor? 在初始化列表中使用空构造函数初始化父类? - Initialize parent class with empty constructor in initializer list? 为什么不能从初始化列表初始化我的类,即使它派生自 std::list? - Why can't initialize my class from an initializer list even if it derives from std::list? 类成员初始化程序使用错误检查初始化ifstream? - Class member initializer to initialize ifstream with error check? 为什么在为 Matrix 类实现初始化列表构造函数时不能访问这个数组? - Why can I not access this array whilst implementing an initializer list constructor for a Matrix class? 为什么不能在构造函数初始值设定项列表中使用&#39;this&#39;指针? - Why can't the 'this' pointer be used in the constructor initializer list? 如何在构造函数初始值设定项列表中初始化std :: unique_ptr对象的类成员std :: vector? - How do I initialize a class member `std::vector` of `std::unique_ptr` object in the constructor initializer list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM