故事背景:
最近在看邓俊辉老师的书《数据结构(C++语言版》。不得不说这本书写的太好了,强烈推荐大家看看。
我以前也学过C++,基础的语法还是知道的,也知道C++里模板的用法。所以我满以为凭这点底子看这本书的示例代码应该是没问题的。我还特地找了一个C++在线编译器。这个在线编译器支持多种版本的C++语法,还支持多文件。
在看到第三章列表节点模板类的示例代码时,我看不懂了。代码是这样的:
typedef int Rank; //秩#define ListNodePosi(T) ListNode* //列表节点位置template struct ListNode { //列表节点模板类(以双向链表形式实现)// 成员T data; ListNodePosi(T) pred; ListNodePosi(T) succ; //数值、前驱、后继// 极造函数ListNode() {} //针对header和trailer的构造ListNode( T e, ListNodePosi(T) p = NULL, ListNodePosi(T) s = NULL) : data(e), pred(p), succ(s) {} //默认构造器// 操作接口ListNodePosi(T) insertAsPred(T const& e); //紧靠当前节点之前插入新节点ListNodePosi(T) insertAsSucc(T const& e); //紧随当前节点之后插入新节点};
看不懂的有两句(凭什么可以这样写?为什么我写不出来?):
#define ListNodePosi(T) ListNode<T>*
ListNodePosi(T) pred;
先来看看微软msdn对#define的语法解释:
#define Directive (C/C++)
#define identifier token-stringopt#define identifier ( identifieropt,...,identifieropt)token-stringopt
The
#define
directive causes the compiler to substitute token-string for each occurrence of identifier in the source file. The identifier is replaced only when it forms a token. That is, identifier is not replaced if it appears in a comment, in a string, or as part of a longer identifier. For more information, see .