歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++ 初學進階

C++ 初學進階

日期:2017/3/1 9:42:13   编辑:Linux編程

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++ Primer Plus 第6版 中文版 清晰有書簽PDF+源代碼 http://www.linuxidc.com/Linux/2014-05/101227.htm

讀C++ Primer 之構造函數陷阱 http://www.linuxidc.com/Linux/2011-08/40176.htm

讀C++ Primer 之智能指針 http://www.linuxidc.com/Linux/2011-08/40177.htm

讀C++ Primer 之句柄類 http://www.linuxidc.com/Linux/2011-08/40175.htm

Copyright © Linux教程網 All Rights Reserved