C C 中 和 巨集

2021-07-23 17:43:58 字數 1070 閱讀 6575

在c語言/c++中,巨集(macro)是屬於編譯時期(而非執行時期)的概念,採用關鍵字define進行定義。它只是一種簡單的字串替換,根據是否帶引數分為無參和帶參。

它的作用還是很大的,比如

提高可移植性,可讀性,方便性

等等,常見就是替換變數,防止重複包含標頭檔案等

#define max 10

#ifndef __head_h__

#define __head_h__

//標頭檔案內容

#endif

這些都不多提,今天主要總結

一下我不太熟悉的巨集特殊符號及慣用法即#和##。

首先是#,它是使用預處理器將乙個巨集引數轉換為乙個字串,即#argument被翻譯為「argument」。看下面一段**:

#define n 10

#define print_macro(format, value) \

printf("the value of " #value " is " format "\n", value)

#define to_string(s) #s

int main()

結果顯示

而對於巨集##,它是一種分隔連線方式,它的作用是先分隔,然後進行強制連線。

#define cat(a, b) a##b

int main()

在c++中如果寫個test類,裡面有多個形如_data1, _data2, _data3等私有成員變數以及對應的get/set函式,如果乙個個寫,發現太麻煩了,於是我們可以用##來實現乙個簡化寫法,具體如下:

#define  get_set_parameter_macro(type, name) \

private: \

type _##name; \

public: \

void set##name(type name) \

type get##name()

class test ;

int main()

C,C 巨集中 和

巨集中的 的功能是將其後面的巨集引數進行字串化操作 stringizing operator 簡單說就是在它引用的巨集變數的左右各加上乙個雙引號。如定義好 define string x x之後,下面二條語句就等價。char pchar hello char pchar string hello 還...

c c 巨集中 和 的用法

kennyhe 發表於 2007 2 13 12 25 57 一 一般用法 我們使用 把巨集引數變為乙個字串,用 把兩個巨集引數貼合在一起.用法 i nclude i nclude using namespace std define str s s define cons a,b int a e ...

C C 巨集中「 和 」的用法

一 一般用法 我們使用 把巨集引數變為乙個字串,用 把兩個巨集引數貼合在一起.用法 i nclude i nclude using namespace std define str s s define cons a,b int a e b int main 二 當巨集引數是另乙個巨集的時候 需要注...