image

qke 奇客

最近又比较闲了,想研究一下开源的技术,又重新玩起了C++,#define回顾

自己当复习,也分享一下知识,做个记号,温故而知新

如果是学C或C++的朋友,一定忘了不了#这个符号。

它是个预编译符号:

# 和 ## 操作符是和#define宏使用的. 使用# 使在#后的首个参数返回为一个带引号的字符串.

例:

#define pi 3.1314

将cout<<pi<<endl;

解释成:cout<<3.1314<<endl;

#define To_String(s) # s

将 cout<<To_String(shaoxiong)<<endl;

解释成cout<<”shaoxiong”<<endl;

#define concatenate(x,y) x##y

将 cout<<condatenate(xy,2)<<endl;

解释成cout<<12<<endl;

测试代码:

下载: main.cpp
  1. #include <iostream>
  2. #define pi 3.1314
  3. #define To_String(s) #s
  4. #define concatenate(x,y) x##y
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9.     cout<<"PI is:"<<pi<<endl;
  10.     cout<<To_String(shaoxiong)<<endl;
  11.     cout<<concatenate(1,2)<<endl;
  12.  
  13.     return 0;
  14. }

这些都是一些预处理指令,可以理解为它们的作用是在代码文本级上的,相当只是个替换符号。

接下来我还会介绍另外一些预编译指令。

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>