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

#define

2013年10月05日 ⁄ 综合 ⁄ 共 1153字 ⁄ 字号 评论关闭

说明:预处理指令,用于各种定义

语法:
#define 标识符 替换列表
#define 标识符[(标识符, 选择... , 标识符 )] 替换列表

标识符必须符合标识符命名规则。替换列表可以是任意字符序列,如数字、字符、字符串字面量、表达式等等。

注意,预处理指令 #define 的最后面没有分号(;)

定义简单的常数:定义常量,便于修改
 #define N 1000
 等效于 const int N = 1000; 但略有不同,define只是简单替换,而不是作为一个量来使用.

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

定义单行宏:主要有以下三种用法.
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”.

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

用于条件编译:(常用形式)
 #ifndef _AAA_H
 #define _AAA_H
 //c/c++代码
 #endif
一些注意事项:
  1、 不能重复定义.除非定义完全相同.#define A(x) … 和#define A 是重复定义.
  2、 可以只定义符号,不定义值.如#define AAA

抱歉!评论已关闭.