无法将 ifstream 对象声明为我的类中的成员
Can't get ifstream object declared as a member in my class
我正试图在类函数的多个位置读取文件。因此,我认为在头文件中(私下(声明对象是明智的,但在我这样做之后,它就不再工作了
我确实使用了搜索功能,发现复制构造函数可能是个问题,但我真的不知道它们做什么,也不知道为什么我需要更改它们(如果我的代码中是这样的话(
命令.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;
相关文章:
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- C++-我可以创建另一个类的成员并在构造函数中使用它吗
- 我应该声明所有不抛出 noexexcept 的成员/函数吗?
- 当我调用对象的方法时,对象的成员会发生变化
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- 为什么我的 FreeRTOS 任务看不到类成员?
- 为什么我可以改变常量对象中的成员变量,这是返回常量对象函数的结果?
- 我无法删除 wxApp 类的成员变量
- 我可以使用在类构造函数中初始化的流类型的成员变量吗?
- 我想知道我是否可以将一个类分配给特定的成员数据并创建该类的实例
- 我可以说服自动生成的构造函数将我的 POD 类成员归零吗?
- 我的类中应该有一个Allocator作为成员变量吗
- 成员函数的"this"参数具有"const"类型,但我的函数实际上不是"const"
- 我的编译器是否忽略了我未使用的静态thread_local类成员
- 我写了一个类,它总是将其函数参数委托给它的成员,我该如何改进代码
- 如何制作指针来调用我的成员函数
- 声明我的成员函数参数/参数
- 为什么我无法访问我的成员变量
- 我的成员模板函数声明有什么问题
- 试图找出为什么我的成员初始化列表不工作