您的位置:首页 > 其它

设计一个追踪类

2013-10-24 22:27 253 查看
设计一个追踪类

——本文来自于《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;
}




该程序比较简单,不多做解释。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: