无法将 ifstream 对象声明为我的类中的成员

Can't get ifstream object declared as a member in my class

本文关键字:我的 成员 声明 ifstream 对象      更新时间:2023-10-16

我正试图在类函数的多个位置读取文件。因此,我认为在头文件中(私下(声明对象是明智的,但在我这样做之后,它就不再工作了

我确实使用了搜索功能,发现复制构造函数可能是个问题,但我真的不知道它们做什么,也不知道为什么我需要更改它们(如果我的代码中是这样的话(

命令.h:

class command
{
public:
command();
~command();
void printCommands() const;
private:
std::ifstream file;
}

Command.cpp

command::command(){
file.open("commands.txt");
}
command::~command()
{
file.close();
}
void command::printCommands() const
{
int i = 0;
std::string line;
std::cout <<"Command list:nn";
while (getline(file,line))
{
    std::cout << line <<endl<<endl;
}
}

这只是代码的一部分,但基本上我在getline函数中得到了一个错误

我收到这个错误

 error C2665: 'std::getline' : none of the 2 overloads could convert all the argument types
 std::basic_istream<_Elem,_Traits> &std::getline<char,std::char_traits<char>,std::allocator<_Ty>>      (std::basic_istream<_Elem,_Traits> &&,std::basic_string<_Elem,_Traits,_Alloc> &)

编辑1:

我忘了,如果我真的移动

 std::ifstream file;

在cpp函数(我使用getline函数的地方(中,它可以毫无问题地工作,但它不应该私下处理解密吗?

您的command::printCommands()被声明为const。由于file是一个成员,您正试图将const ifstream&作为非常数std::istream&参数(由std::getline接收(传递。

转换在调用时丢失了const限定符(因此编译失败并出现错误(。

若要修复此问题,请从command::printCommands()中删除const限定符。

void command::printCommands() const

该行声明printCommands()为常量函数。即不改变command对象的一个。从输入流中读取是一种改变,因此如果输入流是command的一部分,那么从中读取必然会改变command

我不知道你的程序,所以我不能说以下是否是个好主意,但它应该会让错误消失:将file声明为可变成员:

mutable std::ifstream file;