c++ - 在类中初始化 ofstream

标签 c++

我不想在 main() 中构造 ofstream。这是我所做的,但它没有编译:

#include <fstream>
using namespace std;
class test
{
private:
    ofstream &ofs;
public:
    test(string FileName);
    void save(const string &s);
};
//----------------
test::test(string FileName)
    : ofs(ofstream(FileName.c_str(),ios::out))
{
}
//----------------
void test::save(const string &s)
{
    ofs << s;
}
//----------------
//Provide file name and to-be-written string as arguments.
int main(int argc,char **argv)
{
    test *t=new test(argv[0]);
    t->save(argv[1]);
    delete t;
}

test.cpp: In constructor ‘test::test(std::string)’:
test.cpp:13: error: invalid initialization of non-const reference of type ‘std::ofstream&’ from a temporary of type ‘std::ofstream’

如何修复代码?

最佳答案

表达式 ofstream(FileName.c_str(),ios::out)) 创建一个不能绑定(bind)到非常量引用的临时对象。

你为什么不这样做呢(同时阅读评论):

class test 
{
    private:
        ofstream ofs; //remove & ; i.e delare it as an object
    public:
        test(string const & FileName); // its better you make it const reference
        void save(const string &s);
};

test::test(string const & FileName)  // modify the parameter here as well
    : ofs(FileName.c_str(),ios::out) // construct the object
{

}

希望对您有所帮助。

关于c++ - 在类中初始化 ofstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9450878/

相关文章:

c++ - 在一个变量中保存两种不同的返回类型

c++ - 将 std::string_view 与需要以空字符结尾的字符串的 api 一起使用

c++ - 有没有更好的方法来处理为层次结构中的类分配身份以供运行时使用?

c++ - 在 Linux 上使用 CMake 构建 Google glog

c++ - 调用内核后使用 queue.flush() 和 queue.finish() 的正确方法是什么?

c++ - 我的应用程序需要并行化还是多线程化

c++ - 如何从 vector 或数组中选择最常见的数字?(TOP5 toplist) C++

c++ - 使用锁和 STL 算法对 c++ vector 进行排序,还是编写更复杂的无锁算法?

c++ - 从笛卡尔坐标到极坐标

c++ - 为什么编译器不抛出编译错误?