在结构中使用fstream,错误

Using fstream in struct, errors

本文关键字:fstream 错误 结构      更新时间:2023-10-16

我正在尝试初始化结构中的文件输出流。应该创建的文件有一个我想在主函数中定义的名称,即:

#include <iostream>
#include <fstream>
struct str {
std::ofstream fs;
};
int main() {
    str G;
    G.fs("hello.txt",std::ios::app);
}

这让我:错误:对"(std::fstream{aka std::basic_stream})(const char[10],const openmode&)"|的调用不匹配

如何做对?

初始化构造函数不能以这种方式使用。试试这个:
int main() {
    str G;
    G.fs.open("hello.txt",std::ios::app);
}