c++ - ostream 和 fstream 的父类(super class)

标签 c++ c++11 iostream

我正在尝试使用包装器类在 C++ 中创建我自己的日志记录类,在该类中我重载了 operator<< 并将其发送到 cout。现在我想改变它,这样当我创建该类的实例时,我可以传递和参数将数据记录在 std::cout 或我创建的某些文件中。 fstream 和 ostream 的父类(super class)的确切类型是什么?我尝试使用 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;
};

最佳答案

使用基类 std::ostream 这是 basic_ostream<char> 的 typedef ,引用: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;
};

关于c++ - ostream 和 fstream 的父类(super class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48441206/

相关文章:

c++ - push_back()文件系统::path的.string()。data()的怪异行为导致生成 “vector<const char *>”

c++ - 使函数返回内联临时对象?

c++ - 从另一个线程发出信号的最快方法

c++ - c++调用基类的ostream友元函数

c++ - Operator() 的部分特化

c++ - 如何删除 vector 中的重复项(不排序)C++

python - 我使用 python3.5 和 OpenCV 3.1.0,OpenCV 函数 cv2.countNonZero(img) 我得到一个错误

c++ - 如何创建指向模板成员函数的函数指针?

c++ - 将数据从 C++ 传递到 gnuplot 示例(使用 Gnuplot-iostream 接口(interface))

c++ - 输入被切断