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");
}
下面例子将实现这一功能;
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
- C/C++进阶[1]
- C/C++进阶[2]
- C/C++进阶[3]
- C/C++进阶[4]
- C/C++进阶[5]
- C语言进阶
- C语言进阶
- Linux C 进阶过程
- C++primer函数进阶
- C语言进阶
- C语言进阶3
- C语言学习进阶
- C语言进阶
- c编程进阶
- C语言程序设计进阶
- C基础知识进阶(上)
- C语言进阶
- c to c++进阶
- Lucene3.6学习记录 HelloWorld (一)
- 最小边覆盖与最小路径覆盖的联系与区别
- 查找元素
- BYOD时代下的无代理准入控制系统
- Windows API OpenClipboard 剪切板
- C++ 进阶
- OC学习(一)
- list去重的两种方法大比拼
- Best Time to Buy and Sell Stock【找出最大利润】
- Eclipse中java和Xml文件字体大小调整:
- No.05 Xcode(5.1.x) 服务器消息推送
- 如何在centos下,安装ffmpeg和vlc
- 图 基本术语
- Windows7如何开启telnet服务