【问题标题】:Superclass for ostream and fstreamostream 和 fstream 的超类
【发布时间】:2018-01-25 10:57:08
【问题描述】:

我正在尝试使用包装类在 C++ 中创建自己的日志记录类,在该包装类中我重载了 operator

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::basic_ostream 是一个模板,std::ostream 可能是你想要的。
  • 发布有关构建错误的问题时,请始终包含您遇到的错误。将它们作为文本完整完整地复制,然后将它们不加修改地粘贴到问题正文中。请花一些时间到read about how to ask good questions
  • 另外,尝试查找a good input/output reference 可能也会对您有所帮助。

标签: c++ c++11 iostream


【解决方案1】:

使用基类std::ostream,它是basic_ostream&lt;char&gt;的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;
};

【讨论】:

    【解决方案2】:

    fstreamostream 的超类的确切类型是什么?

    它是std::ostream,它是std::basic_ostream&lt;char&gt; 的别名。请参阅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;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-10
      相关资源
      最近更新 更多