类中的 ifstream 变量
ifstream variable in class
我有我的类,里面必须有ifstream文件。
我不知道如何在类标题中呈现它
一个:
class MyClass
{
...
ifstream file;
...
}
乙:
class MyClass
{
...
ifstream& file;
...
}
我知道 ifstream 必须在十度中获取路径,那么我该怎么做呢?
另外,我如何使用它打开文件?
编辑:
我想要第一种方法,但是我如何语法地使用它?
假设这是标题(它的一部分)
class MyClass
{
string path;
ifstream file;
public:
MyClass();
void read_from_file();
bool is_file_open();
...
}
函数
void MyClass::read_from_file()
{
//what do I do to open it???
this->file.open(this->path); //Maybe, IDK
... // ?
}
您很可能想要第一个选项。第二个是对其他ifstream
对象的引用,而不是属于MyClass
的ifstream
。
您无需立即为ifstream
提供路径。你可以稍后调用ifstream
的open
函数并给它一个路径。但是,如果要在初始化时立即打开ifstream
,则需要使用构造函数的初始化列表:
MyClass() : file("filename") { }
如果需要构造函数采用文件名,只需执行以下操作:
MyClass(std::string filename) : file(filename) { }
在构造函数中初始化它:
class my_class {
public:
my_class(char const* path) : file(path) {
}
my_class(std::string const& path) : my_class(path.c_str()) {
}
private:
std::ifstream file;
};
另请参阅权威C++书籍指南和列表。
相关文章:
- 尝试在 C++ 中为 ifstream 提供一个变量
- 如何使用 ifstream 检查文件中变量的类型?
- 将Filtering_istream类型的变量施放为ifstream类型
- Ifstream:打开可使用变量访问的文件
- ifstream 代码不会将输入放入变量中
- 尝试将数字放入 ifstream 文件中的变量中
- c++从ifstream中读取一行的最后一个变量
- 类中的 ifstream 变量
- C++ 使用带有变量作为参数的自定义 ifstream 类时出错
- ifstream变量循环不打印任何内容
- 带有ifstream和ofstream的变量文件名
- C++如何将变量用于 ifstream
- Visual C++ IFstream读取文件并分配给变量
- C++在同一对象的成员之间传递 ifstream 变量
- 在C++中取消设置变量时,文件打开(ifstream)不正确
- 如何使用 ifstream 正确从文件中读取无符号的 int 变量
- 如何将 ifstream&return from 方法分配给变量?
- 实例化一个不使用变量的ifstream对象
- 基于ifstream设置变量
- 将ifstream中的一行读入字符串变量