通過#define連接字串的特殊方法[轉]

來源:互聯網
上載者:User

標籤:

//在#define中,標準只定義了#和##兩種操作。#用來把參數轉換成字串,##則用來串連兩個前後兩個參數,把它們變成一個字串。

#define Conn(x,y)    x##y   //串連x,y

#define ToChar(x)    #@x    //加單引號

#define ToString(x)  #x     //加雙引號

 

    最近看com相關的資料,看到CCmdTarget實現com介面的時候,去讀了一些宏的定義,在afxdisp.h標頭檔中

#define BEGIN_INTERFACE_PART(localClass, baseClass) \
class X##localClass : public baseClass \

本來這個宏定義很容易理解的,但是這裡多出個X##,我真沒見過這種用法,不曉得它是什麼用意。
後來問了幾個朋友也都不知道。

你知道嗎?

也許你也不知道~呵呵,最後我還是找到了相關的資料,解讀了這個define,還順便認識了另外兩個不常用的define

#define Conn(x,y) x##y
#define ToChar(x) #@x
#define ToString(x) #x

x##y表示什嗎?表示x串連y,舉例說:
int n = Conn(123,456);   結果就是n=123456;
char* str = Conn("asdf", "adf")結果就是 str = "asdfadf";
怎麼樣,很神奇吧

再來看#@x,其實就是給x加上單引號,結果返回是一個const char。舉例說:
char a = ToChar(1);結果就是a=‘1‘;
做個越界實驗char a = ToChar(123);結果是a=‘3‘;
但是如果你的參數超過四個字元,編譯器就給給你報錯了!error C2015: too many characters in constant   :P

最後看看#x,估計你也明白了,他是給x加雙引號
char* str = ToString(123132);就成了str="123132";

最後留幾個小實驗給大家去測測:
#define Dec(x,y) (x-y)
int n = Dec( A(123,1), 1230);
n = Conn(123, Conn(123,332) );
char* str = A("12", ToString( Dec(3,1));
結果會如何呢? 嘿嘿嘿嘿~


其他一些雜七雜八的東西:
我先定義了一個宏
#define TE text
我想再定義一個宏,能將TE變為字串("text").
即定義:
#define STR(str) ??? //使用STR(TE)時能替換為"text"。
請問???部分怎麼實現呢?用#str是達不到目的的了,用‘"‘##str##‘"‘也不對。

#不能做二次替換,可以再定義一個中間宏
#define TE text
#define AD TE
#define STR(AD) #AD
試試

直接定義兩個宏得了!
#define TE text
#define TE_S "text"


#define STR abc
char arr[10] = "STR";
為什麼arr數組中是STR而不是abc,define不是簡單的字元替換嗎?

#define A "aaa"
#define B "bbb"A
我對macro這個東西不大熟悉……不過這樣可以成功printf("%s\n",B);


在#define中,標準只定義了#和##兩種操作。#用來把參數轉換成字串,##則用來串連兩個前後兩個參數,把它們變成一個字串。
#include <stdio.h>
#define paster( n ) printf( "token " #n" = %d\n ", token##n )
int main()
{
int token9=10;
paster(9);
return 0;
}
輸出為
[[email protected] src]$ ./a.out
token 9 = 10

補充一點: 在用#define 定義時 ,可以用斜杠("\") 續行.與vb中的底線(" _")作用同.
比如:
#define add1( x, y ) ( x + y)
也可以表示成 :
#define add1(x,y) \
(x + y )

3個普通用法
1.
C: #define X 100   ----> C++: const int x=100;

2.
C: #define MAX(a,b) ((a)>(b)?(a):(b))
C++: inline int max(int a,int b){ return a>b?a:b;}

3.
     #ifndef NULL
         #define NULL ((void*)0)
     #endif

     #ifndef _myheadfile_h
         #define _myheadfile_h
     #endif

通過#define連接字串的特殊方法[轉]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.