【发布时间】:2015-06-14 12:40:45
【问题描述】:
我想实现一个接收文件路径作为参数的单例类。我尝试编写以下代码。我知道它不起作用而且不好,但我找不到原因..
class OutputData {
std::fstream ofile;
std::ostream iout;
static OutputData *odata;
OutputData(const char* path):iout(std::cout), ofile(path) {
if (ofile.is_open()) {
iout = ofile;
}
}
public:
static void print(std::string s) {
iout << s;
}
};
在.cpp中
OutputData *OutputData::odata = nullptr;
从现在开始,我希望每个班级都能够写入该流。
谢谢
【问题讨论】:
-
为什么要为此使用单例,而不仅仅是为
OutputData提供流operator<<()重载?? -
因为我的项目中有十几个类需要使用该流
-
你没有明白我在说什么:将它作为参考传递而不是使用单例,其他一切都会不必要地使你的设计混乱(尤其是在大类层次结构中)。