Can't declare ifstream class member in header file

和自甴很熟 提交于 2019-12-19 10:25:40

问题


I am trying to declare an ifstream object in a header file as is shown but I get an error saying that it cannot be accessed. I have tried various things such as making it into a pointer instead, initialising in the .c file etc. but my code can't seem to get part the declaration of it.

ReadFile.h:

#ifndef READFILE_H
#define READFILE_H

#include "cv.h"
#include "highgui.h"
#include <iostream>
#include <fstream>

class ReadFile{

private:
    std::ifstream stream;

public:
    std::string read();

    ReadFile();                                 // Default constructor
    ~ReadFile();                                    // Destructor
};

#endif

ReadFile.c: #include "ReadFile.h"

ReadFile::ReadFile(){
stream.open("./data.txt");
}

ReadFile::~ReadFile(){
stream.close();
}

The error that I am getting is:

Error   9   error C2248: 'std::basic_ifstream<_Elem,_Traits>::basic_ifstream' : cannot access private member declared in class 'std::basic_ifstream<_Elem,_Traits>' c:\users\Bob\documents\project\models\readfile.h    23  1   Project

The output is:

1>c:\users\Bob\documents\project\models\readfile.h(23): error C2248: 'std::basic_ifstream<_Elem,_Traits>::basic_ifstream' : cannot access private member declared in class 'std::basic_ifstream<_Elem,_Traits>'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 11.0\vc\include\fstream(827) : see declaration of 'std::basic_ifstream<_Elem,_Traits>::basic_ifstream'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          This diagnostic occurred in the compiler generated function 'ReadFile::ReadFile(const ReadFile &)'

The error occurs when std::ifstream stream; is included and will disappear when this line is removed. What could be causing this error? Have I missed something really obvious or is there more to it?


回答1:


The problem is that std::ifstream doesn't have a public copy constructor (because copying one wouldn't make sense) but the compiler-generated copy constructor for your class wants to use it.

It doesn't have any available assignment operator for the same reason (i.e. copying a std::ifstream is nonsense).

You should disallow copying and assignment for your class as well.

A simple way is to add

private:
    ReadFile(const ReadFile&);
    ReadFile& operator=(const ReadFile&);

to your class, if you're using C++03.

In C++11, use the = delete syntax.

public:
    ReadFile(const ReadFile&) = delete;
    ReadFile& operator=(const ReadFile&) = delete;


来源:https://stackoverflow.com/questions/20385588/cant-declare-ifstream-class-member-in-header-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!