C++:初始化初始化列表中对 ofstream 的引用
C++: initialize reference to ofstream in initialization 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>}’
我该怎么做?感谢您的任何建议!
您可以存储指针和标志所有权:
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。
要修复您的错误:
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 ";
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- C++使用整数的压缩数组初始化对象
- C++初始化基类
- 多成员Constexpr结构初始化
- 复制列表初始化的隐式转换的等级是多少
- 内联映射初始化的动态atexit析构函数崩溃
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 没有用于初始化C++中的变量模板的匹配构造函数
- 在未初始化映射的情况下,将值插入到映射的映射中
- C++成员初始化
- 为什么在C++中首先初始化成员类
- 同时具有"聚合初始化"和"模板推导"
- 初始化具有非默认构造函数的std::数组项的更好方法
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 在 c++ 中初始化 std::ofstream 的向量
- 在构造函数类中初始化 ofstream,仅适用于 c++11
- C++:初始化初始化列表中对 ofstream 的引用
- 如何初始化对 std::ofstream 的静态引用