程序最美(寻路)

你还在坚持练习你的技术吗?运动员天天训练,音乐家也会演练更难的曲章。你呢?

设计一个追踪类

设计一个追踪类

——本文来自于《C++沉思录》中的例子。

         用C++设计思想制作一个追踪类,实现功能:

         1.基本的追踪

         2.追踪开关

         3.对于输出信息指定输出文件

         程序如下:

// 追踪类
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

class MyTrace
{
private:
    bool  ok_;
    FILE* f_;

public:
    MyTrace() : ok_(true), f_(stdout) {}
    MyTrace(FILE* const f) : ok_(true), f_(f) {}

    void Print(const string& msg)
    {
        if (ok_)
        {
            fprintf(f_, "%s", msg.c_str());
        }
    }
    
    void On()
    {
        ok_ = true;
    }

    void Off()
    {
        ok_ = false;
    }
};

int main()
{
    MyTrace mt;
    mt.Print("Begin main()\n");
    
    mt.Print("Test On()\n");

    mt.Off();

    mt.Print("Test Off()\n");

    mt.On();

    mt.Print("Test On() again\n");

    // ...

    mt.Print("End main()\n");
    return 0;
}

 

         该程序比较简单,不多做解释。

posted on 2013-10-24 22:27  unixfy  阅读(227)  评论(0编辑  收藏  举报

导航