欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > c/c++ >内容正文

c/c++

C++ 进阶

发布时间:2025/5/22 c/c++ 143 豆豆
生活随笔 收集整理的这篇文章主要介绍了 C++ 进阶 小编觉得挺不错的,现在分享给大家,帮大家做个参考.
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");
}

总结

以上是生活随笔为你收集整理的C++ 进阶的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。