【问题标题】:How to overload printf or cout如何重载 printf 或 cout
【发布时间】:2011-05-03 22:50:55
【问题描述】:

我在我的程序中使用 cout 语句进行调试。我想做一个像它一样工作的函数,或者像 printf 一样工作,但对全局变量敏感。如果这个全局变量为真,那么它将打印到屏幕上。如果它是假的,那么它不会打印任何东西。是否已经有这样的功能?如果没有,那怎么做呢?

【问题讨论】:

标签: c++ debugging function


【解决方案1】:

类似这样的:

int myPrintf(const char* format, ...) 
{
  if (globalCheck == 0)
    return 0
  va_list vl;
  va_start(vl, format);
  auto ret = vprintf(format, vl);
  va_end(vl);
  return ret;
}

va_start 和va_end 将... 中的参数封装在va_list 中。有了这个va_list,您就可以使用vprintf,它是printf 的一个变体,专为这种需求而设计。

旁注 - 通常使用全局变量是不好的做法。更好的做法是将它封装在这样的类中 -

class ConditionalPrinter {
public:
  ConditionalPrinter() : m_enable(true) {}
  void setOut(bool enable) { m_enable = enable; }
  int myPrintf(const char* format, ...);
private:
  bool m_enable;
}

然后检查 m_enable 而不是全局变量。 this 的用法如下所示:

ConditionalPrinter p;
p.myPrintf("hello %d", 1);   // printed
p.setOut(false);
p.myPrintf("hello2 %d", 1);  // not printed

....

【讨论】:

    【解决方案2】:

    不要自己写。做正确的事情比你想象的要难多。当您需要线程和效率时,就更难了。使用现有的日志库之一,例如:

    【讨论】:

      【解决方案3】:

      正如其他人所说,有几个不错的日志框架可用。但是,如果你想自己滚动,首先要注意的是 cout 不是一个函数,它是一个流。函数是operator<<。您可以执行以下操作:

      /* trace.h */
      extern ostream debug;
      
      void trace_init();
      void trace_done();
      
      /* trace.cpp */
      #include "trace.h"
      ostream debug(cout.rdbuf());
      static ofstream null;
      
      void trace_init()
      {
          null.open("/dev/null");
          if(output_is_disabled) {  // put whatever your condition is here
              debug.rdbuf(null.rdbuf());
          }
      }
      
      void trace_done()
      {
          null.close();
      }
      

      如果您在没有/dev/null 的平台上,您可能需要稍作调整。它的作用是让你写

      debug << "here's some output << endl;
      

      如果您启用了输出,它将写入 cout。如果没有,它会写信给/dev/null,在那里你什么都看不到。

      就此而言,您可以将 cout 的 rdbuf 设置到您看不到该输出的某个位置,但我认为这是一个非常糟糕的主意。创建新流可以让您在控制输出方面更加灵活。

      【讨论】:

        猜你喜欢
        • 2011-06-26
        • 2020-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-19
        • 2011-02-12
        • 1970-01-01
        • 2013-03-24
        相关资源
        最近更新 更多