當(dāng)前位置:
首頁(yè) >
C++ 进阶
發(fā)布時(shí)間:2025/5/22
201
豆豆
C++面對(duì)對(duì)象設(shè)計(jì)其中常常涉及到有關(guān)跟蹤輸出的功能,這是C++進(jìn)階的一個(gè)非常基礎(chǔ)的問(wèn)題;
以下樣例將實(shí)現(xià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;
};
上述樣例中用一個(gè)noisy跟蹤輸出;
另外,因?yàn)檫@些成員函數(shù)定義在Trace類(lèi)自身的定義內(nèi),C++會(huì)內(nèi)聯(lián)擴(kuò)展它們。所以就使得即使在不進(jìn)行跟蹤的情況下。在程序中保留Trace類(lèi)的對(duì)象也不必付出多大的代價(jià),。僅僅要讓print函數(shù)不做不論什么事情,然后又一次編譯程序,就能夠有效的關(guān)閉全部對(duì)象的輸出;
還有一種改進(jìn):
在面對(duì)對(duì)象時(shí),用戶總是要求改動(dòng)程序;比方說(shuō)。涉及文件輸入輸出流。將要輸出的文件打印到標(biāo)準(zhǔn)輸出設(shè)備以外的東西上;
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類(lèi)中有兩個(gè)構(gòu)造函數(shù)。第一個(gè)是無(wú)參數(shù)的構(gòu)造函數(shù),其對(duì)象的成員f為stdout,因此輸出到stdout。還有一個(gè)構(gòu)造函數(shù)同意明白指定輸出文件!
完整程序:
#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");
}
以下樣例將實(shí)現(xià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;
};
上述樣例中用一個(gè)noisy跟蹤輸出;
另外,因?yàn)檫@些成員函數(shù)定義在Trace類(lèi)自身的定義內(nèi),C++會(huì)內(nèi)聯(lián)擴(kuò)展它們。所以就使得即使在不進(jìn)行跟蹤的情況下。在程序中保留Trace類(lèi)的對(duì)象也不必付出多大的代價(jià),。僅僅要讓print函數(shù)不做不論什么事情,然后又一次編譯程序,就能夠有效的關(guān)閉全部對(duì)象的輸出;
還有一種改進(jìn):
在面對(duì)對(duì)象時(shí),用戶總是要求改動(dòng)程序;比方說(shuō)。涉及文件輸入輸出流。將要輸出的文件打印到標(biāo)準(zhǔn)輸出設(shè)備以外的東西上;
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類(lèi)中有兩個(gè)構(gòu)造函數(shù)。第一個(gè)是無(wú)參數(shù)的構(gòu)造函數(shù),其對(duì)象的成員f為stdout,因此輸出到stdout。還有一個(gè)構(gòu)造函數(shù)同意明白指定輸出文件!
完整程序:
#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");
}
總結(jié)
- 上一篇: ruby 作为嵌入脚本时使用的注意事项
- 下一篇: 《C++面向对象高效编程(第2版)》——