无法在头文件中声明ifstream类成员

问题描述 投票:2回答:2

我正在尝试在头文件中声明一个ifstream对象,如图所示,但我收到一条错误消息,指出无法访问它。我尝试了各种方法,例如将其变成指针,在.c文件中进行初始化等,但是我的代码似乎无法包含其声明。

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();
}

我得到的错误是:

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

输出为:

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 &)'

当包含std::ifstream stream;时发生错误,并且在删除该行时将消失。是什么导致此错误?我是否错过了确实很明显的东西,或者还有更多东西?

c++ ifstream private-members
2个回答
6
投票

问题是,std::ifstream没有公共副本构造函数(因为复制一个没有意义,但是您的类的编译器生成的副本构造函数要使用它。)>

出于相同的原因,它没有任何可用的赋值运算符(即,复制std::ifstream是无意义的。

您也应该禁止复制和分配您的课程。

一种简单的方法是添加

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

对于您的班级,如果您使用的是C ++ 03。

在C ++ 11中,使用= delete语法。

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

0
投票

这本身不是一个答案,但是如果以后有人在尽我所能地挣扎之后遇到这个问题,我还是决定将其发布。

© www.soinside.com 2019 - 2024. All rights reserved.