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

标签 c++ ifstream private-members

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

读取文件.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

读取文件.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; 时会发生错误,并且会在删除此行时消失。是什么导致了这个错误?我错过了一些非常明显的东西还是还有更多?

最佳答案

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

出于同样的原因,它没有任何可用的赋值运算符(即复制 std::ifstream 是无稽之谈)。

您也应该禁止对您的类(class)进行复制和分配。

一个简单的方法是添加

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

到你的类(class),如果你使用的是 C++03。

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

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

关于c++ - 无法在头文件中声明 ifstream 类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20385588/

相关文章:

c++模板不识别类型double

c++ - 当我声明大小为 500 x 500 的 double 矩阵时,为什么会出现堆栈溢出?

f# - 如何使用 f# interactive 访问私有(private)字段/方法/属性

C 私有(private)变量 Get 和 Set 方法

entity-framework - 映射私有(private)属性时的问题

c++ - time.h clock() 在我的硬件上坏了吗?

c++ - 嵌入式 web 控件 (IWebBrowser2),嵌入式 javascript 的 onkeydown 和 onkeyup 不触发

c++ - 打开文件 C++ 时出现问题

c++ - 使用 ifstream 从文本文件打印整数

c++ - 尝试在 std::cout 和 std::ifstream 之间切换