现在的位置: 首页 > 综合 > 正文

Define使用总结

2013年10月12日 ⁄ 综合 ⁄ 共 1047字 ⁄ 字号 评论关闭

1. 定义简单的常数:定义常量,便于修改(切不可在后面加上分号!)

 #define N 1000
 等效于 const int N = 1000; 但略有不同,define只是简单替换,而不是作为一个量来使用.

2. 定义简单的函数:注意多使用括号
 #define MAX(x, y) ((x) > (y)) ?(x) : (y)

3. 定义单行宏:主要有以下三种用法.
   1) 前加##或后加##,将标记作为一个合法的标识符的一部分.注意,不是字符串.多用于多行的宏定义中.例如:
#define A(x)  T_##x
则 int A(1) = 10; //等效于int T_1 = 10;
#define A(x)  Tx##__
则 int A(1) = 10; //等效于int T1__ = 10;
   2) 前加#@,将标记转换为相应的字符,注意:仅对单一标记转换有效(理解有误?)
 #define B(x) #@x
 则B(a)即’a’,B(1)即’1’.但B(abc)却不甚有效.
   3) 前加#,将标记转换为字符串.
 #define C(x) #x
 则C(1+1) 即 ”1+1”.

4. 定义多行宏:注意斜杠的使用,最后一行不能用斜杠.
 #define DECLARE_RTTI(thisClass,superClass)\
  virtual const char* GetClassName()const\ 
  {return #thisClass;}\
  static int isTypeOf(const char*type)\
  {\
   if(!strcmp(#thisClass, type)\
    return 1;\
   returnsuperClass::isTypeOf(type);\
   return 0;\
  }\
  virtual int isA(const char* type)\
  {\
   returnthisClass::isTypeOf(type);\
  }\
  static thisClass*SafeDownCast(DitkObject* o)\
  {\
  if(o&&o->isA(#thisClass))\
    returnstatic_cast<thisClass*>(o);\
   return NULL;\
  }

5. 用于条件编译:(常用形式)
 #ifndef _AAA_H
 #define _AAA_H
 //c/c++代码
 #endif

6. 一些注意事项:
  1) 不能重复定义.除非定义完全相同.#define A(x) … 和#define A 是重复定义.
  2) 可以只定义符号,不定义值.如#define AAA

抱歉!评论已关闭.