详解C++中typedef 和 #define 的区别

1、执行上不同

关键字 typedef 在编译阶段有效,由于是在编译阶段,因此 typedef 有类型检查的功能。

#define 则是宏定义,发生在预处理阶段,也就是编译之前,它只进行简单而机械的字符串替换,而不进行任何检查。

例如:typedef 会做相应的类型检查

typedef unsigned int UINT;  void func(){    UINT value = "abc"; // error C2440: 'initializing' : cannot convert from 'const char [4]' to 'UINT',会编译不通过    cout << value << endl;}

#define不做类型检查:

// #define用法例子:#define f(x) x*xint main(){    int a=6, b=2, c;    c=f(a) / f(b);    printf("%d\n", c);    return 0;}

程序的输出结果是: 36,根本原因就在于 #define 只是简单的字符串替换。

2、功能有差异

typedef 用来定义类型的别名,定义与平台无关的数据类型,与 struct 的结合使用等。

比如:定义一个叫 FALSE 的浮点类型,在目标平台一上,让它表示最高精度的类型为:

typedef long double FALSE;

在不支持 long double 的平台二上,改为:

typedef double FALSE;

在连 double 都不支持的平台三上,改为:

typedef float FALSE;

也就是说,当跨平台时,只要改下 typedef 本身就行,不用对其他源码做任何修改。

#define 不只是可以为类型取别名,还可以定义常量、变量、编译开关等。

3、作用域不同

#define 没有作用域的限制,只要是之前预定义过的宏,在以后的程序中都可以使用。

而 typedef 有自己的作用域。

例如:没有作用域的限制,只要是之前预定义过就可以

void func1(){    #define HW "HelloWorld";}  void func2(){    string str = HW;    cout << str << endl;}

而typedef有自己的作用域:

函数:

void func1(){    typedef unsigned int UINT;}  void func2(){    UINT uValue = 5;//error C2065: 'UINT' : undeclared identifier,在此函数中未定义}

类:

class A{    typedef unsigned int UINT;    UINT valueA;    A() : valueA(0){}};  class B{    UINT valueB;    //error C2146: syntax error : missing ';' before identifier 'valueB'    //error C4430: missing type specifier - int assumed. Note: C++ does not support default-int};

上面例子在B类中使用UINT会出错,因为UINT只在类A的作用域中。

此外,在类中用typedef定义的类型别名还具有相应的访问权限:

class A{    typedef unsigned int UINT;    UINT valueA;    A() : valueA(0){}};  void func3(){    A::UINT i = 1;    // error C2248: 'A::UINT' : cannot access private typedef declared in class 'A'}

默认的typedef为私有,而给UINT加上public访问权限后,则可编译通过。

class A{public:    typedef unsigned int UINT;    UINT valueA;    A() : valueA(0){}};  void func3(){    A::UINT i = 1;    cout << i << endl;}

4、对指针的操作

二者修饰指针类型时,作用不同。

typedef int * pint;#define PINT int *  int i1 = 1, i2 = 2;  const pint p1 = &i1;    //p不可更改,p指向的内容可以更改,相当于 int * const p;const PINT p2 = &i2;    //p可以更改,p指向的内容不能更改,相当于 const int *p;或 int const *p;  pint s1, s2;    //s1和s2都是int型指针PINT s3, s4;    //相当于int * s3,s4;只有一个是指针。  void TestPointer(){    cout << "p1:" << p1 << "  *p1:" << *p1 << endl;    //p1 = &i2; //error C3892: 'p1' : you cannot assign to a variable that is const    *p1 = 5;    cout << "p1:" << p1 << "  *p1:" << *p1 << endl;      cout << "p2:" << p2 << "  *p2:" << *p2 << endl;    //*p2 = 10; //error C3892: 'p2' : you cannot assign to a variable that is const    p2 = &i1;    cout << "p2:" << p2 << "  *p2:" << *p2 << endl;}

结果:

p1:00EFD094 *p1:1p1:00EFD094 *p1:5p2:00EFD098 *p2:2p2:00EFD094 *p2:5

转载于

1、C++数据类型

到此这篇关于详解C++中typedef 与 #define 的区别的文章就介绍到这了,更多相关c++ typedef 与 #define区别内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

却坐在不足一平米的椅子上。

详解C++中typedef 和 #define 的区别

相关文章:

你感兴趣的文章:

标签云: