如何在新类中重载fstream操作符? [重复]

问题描述 投票:0回答:1

我想包装一个新类来生成一个文件,并对新文件进行一些自动资源回收和一些附加操作。 所以我做了一个新课程,比如

class TmpFile {
private:
    std::string tmp_file_name;
    std::ofstream tmp_file;

public:
    TmpFile(const std::string &name) :tmp_file_name(name),
                                       tmp_file(tmp_file_name, ios::out | ios::trunc) {}
    ~TmpFile() {
        tmp_file.close();
        //some operate afterwards using tmp_file
        ...
    }
};

但是有没有办法让操作员重载”<<" to write into file inside "class TmpFile" like

TmpFile f;
f << "asd";
c++ operator-overloading fstream
1个回答
0
投票

如果您只想接受一个带有“<<" operator, you can directly override it:

class TmpFile {
private:
    std::string tmp_file_name;
    std::ofstream tmp_file;

public:
    TmpFile(const std::string &name) :tmp_file_name(name),
                                       tmp_file(tmp_file_name, ios::out | ios::trunc) {}
    ~TmpFile() {
        tmp_file.close();
        //some operate afterwards using tmp_file
        ...
    }

    // here define your operator
    void operator << (const std::string& str) {
        // do something
    }
};

如果你想用一个操作符接受多个对象<< , you can check Eigen库如何实现这样,例如:

f << "asdf", "efsjkfl"
© www.soinside.com 2019 - 2024. All rights reserved.