首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++:初始化列表中对流的引用

C++:初始化列表中对流的引用
EN

Stack Overflow用户
提问于 2013-10-16 15:12:45
回答 2查看 1.6K关注 0票数 1

我读过关于这个题目的多个问题和答案,但不幸的是,这些问题都没有帮助。我想在两个类A和B中使用相同的调试文件输出,其中A的一个实例创建了B的一个实例,我有如下所示:

代码语言:javascript
复制
class A {
public:
    A() : debug("debug.txt") { };
private:
    std::ofstream debug;
}

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

并创建它的实例

代码语言:javascript
复制
B *b = new B(debugUnderlying);

效果很好。但是,我现在希望有一个额外的构造函数,以便能够在不使用ofstream的情况下使用它。然后,对象将打开一个新文件。我明白了,因为我有一个引用,所以我需要在初始化列表中初始化它。我尝试过多种方法:

代码语言:javascript
复制
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*’

代码语言:javascript
复制
B() : debug("debug2.txt") { };

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

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

代码语言:javascript
复制
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>}’

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-10-16 15:38:48

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

代码语言:javascript
复制
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;
};

注:我把“流”替换为“流”。

票数 2
EN

Stack Overflow用户

发布于 2013-10-16 15:30:03

修复您的错误:

代码语言:javascript
复制
B():debug(*(new std::ofstream("debug.txt"))){}

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

So:

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

代码语言:javascript
复制
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()

您还可以像这样定义宏:

代码语言:javascript
复制
#ifdef DEBUG
    #define dbgout Debug::Instance()->outstream()
#else
    // a release version won't create the debug file... 
    #define dbgout //
#endif    

现在,您可以在代码中的任何地方这样使用它:

代码语言:javascript
复制
dbgout<<" put your " << "stream " <<" here ";
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19407140

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档