日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

C++ 进阶

發(fā)布時(shí)間:2025/5/22 201 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++ 进阶 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
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");
}

總結(jié)

以上是生活随笔為你收集整理的C++ 进阶的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。