我正在尝试使用包装类在C ++中创建自己的日志类,其中我重载了运算符<<将它发送到cout。现在我想改变它,所以当我创建该类的实例时,我可以传递和参数,在std :: cout或我创建的某个文件中记录数据。 fstream和ostream的超类的确切类型是什么?我试过std :: ios&,std :: basic_ios&,std :: basic_ostream&并且它们似乎都没有工作(抛出编译错误)。
class myostream {
public:
static int getlogLevel() {
return loglevel;
}
static void setlogLevel(int i) {
loglevel = i;
}
myostream(std::basic_ios& cout, int level)
: _cout(cout), _level(level)
{}
template<class T>
std::ostream& operator<<(T t) {
if(_level >= loglevel) {
_cout << loglevelcolor[_level] << loglevelname[_level] << " " << t << COL_RESET << std::endl;
}
return _cout;
}
private:
static int loglevel;
std::basic_ostream& _cout;
int _level;
};
答案 0 :(得分:2)
使用std::ostream
的typedef基类basic_ostream<char>
,引用:iostream hierarchy。
适合我(std :: cout,std :: ofstream):
#include <iostream>
class myostream {
public:
myostream(std::ostream& out)
: _out(out) {}
template<class T>
std::ostream& operator<<(T t) {
_out << "test" << " " << t << '\n' << 42 << std::endl;
return _out;
}
private:
std::ostream& _out;
};
答案 1 :(得分:0)
fstream
和ostream
的超类的确切类型是什么?
std::ostream
,是std::basic_ostream<char>
的别名。请参阅std::fstream
的类图。
示例:
class myostream {
public:
myostream(int level) // Log into stdout.
: _cout(std::cout), _level(level)
{}
myostream(char const* filename, int level) // Log into a file.
: _file(filename), _cout(_file), _level(level)
{
if(!_file.is_open())
throw std::runtime_error("Failed to open " + std::string(filename));
}
// ...
private:
std::ofstream _file;
std::ostream& _cout;
int _level;
};