C ++:在初始化列表中初始化对ofstream的引用

时间:2013-10-16 15:12:46

标签: c++ pass-by-reference ofstream initializer-list

我已经阅读了有关该主题的多个问题和答案,但不幸的是,他们都没有帮助。我想在两个A和B类中使用相同的调试文件输出,其中A的实例创建B的实例。我有类似的东西:

class A {
public:
    A() : debug("debug.txt") { };
private:
    std::ofstream debug;
}

class B {
public:
    B(std::ofstream &ofs) : debug(ofs) { };
private:
    std::ofstream &debug;
}

并使用

创建一个实例
B *b = new B(debugUnderlying);

效果很好。但是,我现在想要一个额外的构造函数,以便能够在没有ofstream的情况下使用它。然后该对象将打开一个新文件。我明白了,因为我有一个参考,我需要在初始化列表中初始化它。我尝试了很多东西:

B() : debug() { debug.open("debug2.txt"); };

error: invalid initialization of non-const reference of type ‘std::ofstream& {aka std::basic_ofstream<char>&}’ from an rvalue of type ‘const char*’

B() : debug("debug2.txt") { };

error: value-initialization of reference type ‘std::ofstream& {aka std::basic_ofstream<char>&}’

或(很清楚,因为我有一个临时对象)

error: invalid initialization of non-const reference of type ‘std::ofstream& {aka std::basic_ofstream<char>&}’ from an rvalue of type ‘std::ofstream {aka std::basic_ofstream<char>}’

我该怎么做?谢谢你的任何建议!

2 个答案:

答案 0 :(得分:1)

您可以存储指针和标志所有权:

class B {
   public:
   B() : stream(new ...), owner(true) {}
   B(std::ostream& s) : stream(&s), owner(false) {}
   ~B() { if(owner) delete stream; }
   private:
   std::ostream* stream;
   bool owner;
};

注意:我用ostream替换了ofstream。

答案 1 :(得分:0)

修复错误:

B():debug(*(new std::ofstream("debug.txt"))){}

但是:如果你这样做,我想你会忘记删除......

<强>所以:

最好使用单例来包装调试对象

class Debug{
    std::ofstream debug;
    //private ctor, you can't create an object for this class outside
    Debug(const std::string& filename):debug(filename){}
public:
    //only way tou use this class is to call this method
    static Debug* Instance(){
            //the one and only Debug object, created at first use: 
        static Debug theObj("debug.txt");
        return &theObj;
    }
    //write method
    std::ostream& outstream(){
        return debug;
    }
};
//just for simplicity of use:
#define dbgout Debug::Instance()->outstream()

您还可以像这样定义宏:

#ifdef DEBUG
    #define dbgout Debug::Instance()->outstream()
#else
    // a release version won't create the debug file... 
    #define dbgout //
#endif    

现在您可以在代码中的任何位置使用它:

dbgout<<" put your " << "stream " <<" here ";