1. 简化代码书写,尤其使用boost库,iterator或者指针等

typedef boost::filesystem::recursive_directory_iterator bf_rdit;

typedef char * PCHAR;// PCHAR p1, p2; // both p1 and p2 are pointer

2. 实现跨平台

#endif

 

使用

自定义枚举值

enum {SUCCESS, FAIL} ERET;

自定义结构体/类

int length;
} Buffer;

函数指针

  • 全局函数
typedef int (*BinaryOp)(int, int);
int g_Add(int lhs, int rhs)
{
return lhs + rhs;
}

// main function
{
BinaryOp pAdd = g_Add;
cout<<(*pAdd)(1,1)<<endl;
}
  • 类静态成员函数
class CTestMath
{
public:
static int s_Add(int lhs, int rhs);
};
// main function
{
BinaryOp ps_Add = CTestMath::s_Add;
cout<<(*ps_Add)(1,1)<<endl;
}
  • 类成员函数
class CTestMath
{
public:
CTestMath();
virtual ~CTestMath();
int m_Add(int lhs, int rhs);
protected:
private:
};
// main function
CTestMath *pinst = new CTestMath; // must
BinaryOp pm_Add = &CTestMath::m_Add;
cout<<(pinst->*pm_Add)(1,1)<<endl;
delete pinst;
  • 结构体包含同类型指针
如下声明是不对的,因为Node是typedef出来的别名,而typedef是需要根据已有的结构类型来重命名的,现在_Node结构体还没有声明出来,就使用Node来作为类型来声明Next指针是不对的.
int data;
Node * Next;
} Node;
解决方法有1. 先声明_Node结构体,同时使用typedef重命名结构名为Node.
struct _Node * Next;
} Node;
2. 或者先使用typedef来给一个还没有完全声明的类型起新名字,这跟第一钟情况是不一样的,因为它还没有开始创建呢
int data;
PNode Next;
};
不过建议还是用规范的第三种,
struct _Node Node, * PNode;
 

作用域


typedef可以在类中函数中出现,如果出现在类中,还跟public/private/protected的访问规则有关
// 256
}

难点

typedef的使用在模块化编程中使用很多,也会出现很多难懂的声明
int);
a是长度为5的数组指针,数组元素为函数指针,指向int(*)(int, int)函数签名
void (*)());
b是长度为10的数组指针,数组元素为函数指针,指向没有返回值,输入参数为一个函数指针的函数指针
 

误区

与define的区别
define是预编译中字符创形式替换代码,而typedef是具有强类型校验
const PCHAR);
上述代码中如果PCHAR是使用define定义的,那实际函数需要的参数是const char *,而使用typedef将是char * const



 
 
误区

相关文章:

  • 2021-12-13
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-28
  • 2021-07-22
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案