关于宏定义中#与##的用法

来源:互联网 发布:js跨域设置cookie 编辑:程序博客网 时间:2024/04/30 04:07

宏在条件编译以及各种大规模的定义里是非常有用的。

前面Qt源码学习笔记里就有一篇用来介绍宏的定义。

这次主要介绍下宏定义里#,##的作用。

关于宏,注意可以用gcc –E test.cpp来查看预编译之后的结果。

1.先介绍#

主要是字符串替换的作用。将传入的符号转化为字符串

直接上源代码:

#define marco(x)\    ""#x""#include <iostream>#include <string.h>using namespace std;int main(){    cout << marco1(test) << endl;    cout << marco1(abc) << endl;    cout << marco1(helloworld) << endl;    cout << strlen(marco1(test)) << endl;    cout << strlen(marco1(abc)) << endl;    cout << strlen(marco1(helloworld)) << endl;    return 0;}

运行结果:

test
abc
helloworld
4
3
10

 

2.再来看下##

关于这个,前面已经介绍过了。看个简单的例子:

#define PRODUCE(MARCO)\    MARCO(AAA)\    MARCO(BBB)\    MARCO(CCC)#define IMAGE(x)\    IMAGE_##x,#define PIC(x)\    PIC_##x,enum ImageType {    PRODUCE(IMAGE)    IMAGE_COUNT};enum PicType {    PROENUM(PIC),    PIC_COUNT};    #define FUNCTION_DECLARATION(x)\    void Get##x();PRODUCE(FUNCTION_DECLARATION)

看下预编译的结果:

 

C:>gcc -E test.cpp
# 1 "test.cpp"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "test.cpp"
# 12 "test.cpp"
enum ImageType {
    IMAGE_AAA, IMAGE_BBB, IMAGE_CCC,
    IMAGE_COUNT
};

enum PicType {
    PROENUM(PIC),
    PIC_COUNT
};

 


void GetAAA(); void GetBBB(); void GetCCC();