C++ 进阶

来源:互联网 发布:淘宝装修工具2.1下载 编辑:程序博客网 时间:2024/05/19 13:43
C++面对对象设计当中经常涉及到有关跟踪输出的功能,这是C++进阶的一个很基础的问题;

下面例子将实现这一功能;

class Trace {
public:
Trace() { noisy = 0; }
void print(char *s) { if(noisy) printf("%s", s); }
void on() { noisy = 1; }
void off() { noisy = 0; }
private:
int noisy;
};


上述例子中用一个noisy跟踪输出;
另外,由于这些成员函数定义在Trace类自身的定义内,C++会内联扩展它们,所以就使得即使在不进行跟踪的情况下,在程序中保留Trace类的对象也不必付出多大的代价,。只要让print函数不做任何事情,然后重新编译程序,就可以有效的关闭所有对象的输出;

另一种改进:

在面对对象时,用户总是要求修改程序;比如说,涉及文件输入输出流;将要输出的文件打印到标准输出设备以外的东西上;


class Trace {
public:
Trace() { noisy = 0; f = stdout; }
Trace(FILE *ff) { noisy = 0; f = ff; }
void print(char *s) { if(noisy) fprintf(f, "%s", s); }
void on() { noisy = 1; }
void off() { noisy = 0; }
private:
int noisy;
FILE *f;
};

Trace类中有两个构造函数,第一个是无参数的构造函数,其对象的成员f为stdout,因此输出到stdout,另一个构造函数允许明确指定输出文件!

完整程序:

#include <stdio.h>

class Trace {
public:
Trace() { noisy = 0; f = stdout; }
Trace(FILE *ff) { noisy = 0; f = ff; }
void print(char *s) { if(noisy) fprintf(f, "%s", s); }
void on() { noisy = 1; }
void off() { noisy = 0; }
private:
int noisy;
FILE *f;
};


int main()
{
Trace t(stderr);
t.print("begin main()\n");
t.print("end main()\n");
}

0 0