这篇文章的目的是设计提供有关函数执行和类操作调试信息的类
1.一个简单函数跟踪类的设计
class Trace //跟踪类
{
public:
Trace(const char* p, const char* q): bye(q) { cout << p; }
~Trace() { cout << bye; }
private:
const char* bye;
};
//使用示范
void foo()
{
Trace xx("begin foo\n", "end foo\n");
...
}
int main()
{
foo();
//...
}
我们可能想拥有一个调试开关,也可能想在别的地方输出调试信息,于是上述的跟踪类可以改进如下:
class Channel //输出重定向类
{
public:
Channel(ostream* os = &cout) : Trace_File(os) { }
void Reset(ostream *os) { Trace_File = os;}
private:
friend class Trace;
ostream* Trace_File;
};
static const int debug = 1; //debug控制开关
class Trace //跟踪类
{
public:
Trace(const char *s, Channel *c) : m_name(s), m_cp(c)
{
if(debug)
if (m_cp->Trace_File)
*m_cp->Trace_File<<"begin"<<m_name<<endl;
}
~Trace()
{
if(debug)
if (m_cp->Trace_File)
*m_cp->Trace_File<<"end"<<m_name<<endl;
}
private:
Channel *m_cp;
const char* m_name;
};
//使用示范
Channel subsystemX;
subsystemX.reset(0) //关闭跟踪
subsystemX.reset(&some_stream) //重定向跟踪
void foo()
{
Trace xxx("foo", &subsystemX);
//...
}
int main()
{
foo();
//...
}
2.一个对象生成的审计跟踪类的设计
代码如下:
#include <iostream>
using namespace std;
class Obj_trace
{
public:
Obj_trace():ct(++count) { cout<<"Object "<<ct<<" constructed"<<endl; }
~Obj_trace() { cout<<"Object "<<ct<<" destructed"<<endl; }
Obj_trace(const Obj_trace&):ct(++count) { cout<<"Object"<<ct<<" constructed"<<endl; }
Obj_trace& operator=(const Obj_trace&) { return *this; }
private:
static int count;
int ct;
};
int Obj_trace::count = 0;
template<class T>class Array
{
public:
Array(int n = 0):data(new T[n]), sz(n) {}
Array(const Array& a) { Init(a.data, a.sz); }
~Array() { delete[] data; }
Array& operator=(const Array& a)
{
if (this != &a)
{
delete[] data;
Init(a.data, a.sz);
}
return *this;
}
T& operator[](unsigned int index)
{
return data[index];
}
private:
T* data;
int sz;
void Init(T*, int);
};
template<class T>void Array<T>::Init(T* p, int n)
{
sz = n;
data = new T[n];
for (int i=0; i<sz; ++i)
{
data[i] = p[i];
}
}
int main()
{
Array<Obj_trace> x(3);
Array<Obj_trace> y = x;
//y = x;//测试赋值
return 0;
}
运行结果如下:Object 1 constructed
Object 2 constructed
Object 3 constructed
Object 4 constructed
Object 5 constructed
Object 6 constructed
Object 6 destructed
Object 5 destructed
Object 4 destructed
Object 3 destructed
Object 2 destructed
Object 1 destructed