Ted's Blog

Happy coding

typedef的四个用途和两个陷阱

Ted posted @ 2008年8月06日 19:45 in 未分类 with tags typedef c , 2758 阅读

用途一:
定义一种类型的别名,而不只是简单的宏替换。可以用作同时声明指针型的多个对象。比如:
char* pa, pb;  // 这多数不符合我们的意图,它只声明了一个指向字符变量的指针, 
// 和一个字符变量;
以下则可行:
typedef char* PCHAR;  // 一般用大写
PCHAR pa, pb;        // 可行,同时声明了两个指向字符变量的指针
虽然:
char *pa, *pb;
也可行,但相对来说没有用typedef的形式直观,尤其在需要大量指针的地方,typedef的方式更省事。

用途二:
用在旧的C代码中(具体多旧没有查),帮助struct。以前的代码中,声明struct新对象时,必须要带上struct,即形式为: struct 结构名 对象名,如:
struct tagPOINT1
{
    int x;
    int y;
};
struct tagPOINT1 p1; 

而在C++中,则可以直接写:结构名 对象名,即:
tagPOINT1 p1;

估计某人觉得经常多写一个struct太麻烦了,于是就发明了:
typedef struct tagPOINT
{
    int x;
    int y;
}POINT;

POINT p1; // 这样就比原来的方式少写了一个struct,比较省事,尤其在大量使用的时候

或许,在C++中,typedef的这种用途二不是很大,但是理解了它,对掌握以前的旧代码还是有帮助的,毕竟我们在项目中有可能会遇到较早些年代遗留下来的代码。

用途三:
用typedef来定义与平台无关的类型。
比如定义一个叫 REAL 的浮点类型,在目标平台一上,让它表示最高精度的类型为:
typedef long double REAL; 
在不支持 long double 的平台二上,改为:
typedef double REAL; 
在连 double 都不支持的平台三上,改为:
typedef float REAL; 
也就是说,当跨平台时,只要改下 typedef 本身就行,不用对其他源码做任何修改。
标准库就广泛使用了这个技巧,比如size_t。
另外,因为typedef是定义了一种类型的新别名,不是简单的字符串替换,所以它比宏来得稳健(虽然用宏有时也可以完成以上的用途)。

用途四:
为复杂的声明定义一个新的简单的别名。方法是:在原来的声明里逐步用别名替换一部分复杂声明,如此循环,把带变量名的部分留到最后替换,得到的就是原声明的最简化版。举例:

1. 原声明:int *(*a[5])(int, char*);
变量名为a,直接用一个新别名pFun替换a就可以了:
typedef int *(*pFun)(int, char*); 
原声明的最简化版:
pFun a[5]; 

2. 原声明:void (*b[10]) (void (*)());
变量名为b,先替换右边部分括号里的,pFunParam为别名一:
typedef void (*pFunParam)();
再替换左边的变量b,pFunx为别名二:
typedef void (*pFunx)(pFunParam);
原声明的最简化版:
pFunx b[10];

3. 原声明:doube(*)() (*e)[9]; 
变量名为e,先替换左边部分,pFuny为别名一:
typedef double(*pFuny)();
再替换右边的变量e,pFunParamy为别名二
typedef pFuny (*pFunParamy)[9];
原声明的最简化版:
pFunParamy e; 

理解复杂声明可用的“右左法则”:从变量名看起,先往右,再往左,碰到一个圆括号就调转阅读的方向;括号内分析完就跳出括号,还是按先右后左的顺序,如此循环,直到整个声明分析完。举例:
int (*func)(int *p);
首先找到变量名func,外面有一对圆括号,而且左边是一个*号,这说明func是一个指针;然后跳出这个圆括号,先看右边,又遇到圆括号,这说明 (*func)是一个函数,所以func是一个指向这类函数的指针,即函数指针,这类函数具有int*类型的形参,返回值类型是int。
int (*func[5])(int *);
func右边是一个[]运算符,说明func是具有5个元素的数组;func的左边有一个*,说明func的元素是指针(注意这里的*不是修饰 func,而是修饰func[5]的,原因是[]运算符优先级比*高,func先跟[]结合)。跳出这个括号,看右边,又遇到圆括号,说明func数组的 元素是函数类型的指针,它指向的函数具有int*类型的形参,返回值类型为int。

也可以记住2个模式:
type (*)(....)函数指针 
type (*)[]数组指针 
---------------------------------

陷阱一:
记住,typedef是定义了一种类型的新别名,不同于宏,它不是简单的字符串替换。比如:
先定义:
typedef char* PSTR;
然后:
int mystrcmp(const PSTR, const PSTR);

const PSTR实际上相当于const char*吗?不是的,它实际上相当于char* const。
原因在于const给予了整个指针本身以常量性,也就是形成了常量指针char* const。
简单来说,记住当const和typedef一起出现时,typedef不会是简单的字符串替换就行。

陷阱二:
typedef在语法上是一个存储类的关键字(如auto、extern、mutable、static、register等一样),虽然它并不真正影响对象的存储特性,如:
typedef static int INT2; //不可行
编译将失败,会提示“指定了一个以上的存储类”。

 

使用示例:

 

1.比较一:

 

#include <iostream>

using namespace std;

 

typedef int (*A) (char, char);

 

int ss(char a, char b)

{

    cout<<"功能1"<<endl;

    cout<<a<<endl;

    cout<<b<<endl;

    return 0;

}

 

int bb(char a, char b)

{

    cout<<"功能2"<<endl;

    cout<<b<<endl;

    cout<<a<<endl;

    return 0;

}

 

void main()

{

    A a;

    a = ss;

    a('a','b');

    a = bb;

    a('a', 'b');

}

 

2.比较二:

 

typedef int (A) (char, char);

 

void main()

{

    A *a;

    a = ss;

    a('a','b');

    a = bb;

    a('a','b');

}

 

两个程序的结果都一样:

功能1

a

b

功能2

b

a

 

 

*****以下是参考部分*****

 

参考自:http://blog.hc360.com/portal/personShowArticle.do?articleId=57527

 

typedef #define的区别:

 

案例一:

 

通常讲,typedef要比#define要好,特别是在有指针的场合。请看例子:

typedef char *pStr1;

#define pStr2 char *;

pStr1 s1, s2;

pStr2 s3, s4;

 

在上述的变量定义中,s1s2s3都被定义为char *,而s4则定义成了char,不是我们所预期的指针变量,根本原因就在于#define只是简单的字符串替换而typedef则是为一个类型起新名字。

 

 

案例二:

 

下面的代码中编译器会报一个错误,你知道是哪个语句错了吗?

typedef char * pStr;

char string[4] = "abc";

const char *p1 = string;

const pStr p2 = string;

p1++;

p2++;

 

  是p2++出错了。这个问题再一次提醒我们:typedef#define不同,它不是简单的文本替换。上述代码中const pStr p2并不等于const char * p2const pStr p2const long x本质上没有区别,都是对变量进行只读限制,只不过此处变量p2的数据类型是我们自己定义的而不是系统固有类型而已。因此,const pStr p2的含义是:限定数据类型为char *的变量p2为只读,因此p2++错误。

Avatar_small
john 说:
2020年11月29日 21:51

If you have questions related to document protection or your privacy while using services of altounlock, then you should visit https://altounlockpdf.com/blog and get all your questions answered.

Avatar_small
UMAIR 说:
2020年12月09日 15:14

Bihar Board 10th Model Paper 2021 BSEB X Blueprint 2021 Bihar Matric Syllabus & Books 2021 Regardless of whether They are Important Exam Notes BSEB 10th Important Questions 2021 or Model Question Papers Related to Board Exams. To get Class 10th Board Exam Merit Marks and High Marks in Bihar Board Matriculation Examination. Bihar Board 10th Model Paper 2021

Avatar_small
lsm99 说:
2020年12月18日 17:00

our articles are inventive. I am looking forward to reading the plethora of articles that you have linked here. Thumbs up! www.trainingroomsg.com/seminar-room-rental

Avatar_small
lsm99 说:
2020年12月23日 01:02

I’ve been searching for some decent stuff on the subject and haven't had any luck up until this point, You just got a new biggest fan!.. ceramic car coating singapore

Avatar_small
LEGEND SEO 说:
2020年12月31日 16:48

I've been surfing online more than three hours today, yet I never found any interesting article like yours. It's pretty worth enough for me. In my opinion, if all webmasters and bloggers made good content as you did, the web will be a lot more useful than ever before. 123 movie

Avatar_small
lsm99 说:
2021年1月12日 21:56

 

I am happy to find this post Very useful for me, as it contains lot of information. I Always prefer to read The Quality and glad I found this thing in you post. Thanks scr 888

Avatar_small
lsm99 说:
2021年1月14日 00:53

Thanks for sharing this quality information with us. I really enjoyed reading. Will surely going to share this URL with my friends. visit Singapore casino site

Avatar_small
lsm99 说:
2021年1月15日 01:02

This is a great article thanks for sharing this informative information. I will visit your blog regularly for some latest post. I will visit your blog regularly for Some latest post. breezeway desa park city

Avatar_small
lsm99 说:
2021年1月15日 12:24

thank you for your interesting infomation. norske bettingsider

Avatar_small
lsm99 说:
2021年1月15日 19:18

I got too much interesting stuff on your blog. I guess I am not the only one having all the enjoyment here! Keep up the good work. SEO specialist

Avatar_small
lsm99 说:
2021年1月17日 23:56

Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained! Buy Fentanyl Citrate Online

Avatar_small
lsm99 说:
2021年1月21日 23:32

 just found this blog and have high hopes for it to continue. Keep up the great work, its hard to find good ones. I have added to my favorites. Thank You. โรงงานผลิตสบู่

Avatar_small
lsm99 说:
2021年1月30日 20:53

thoughts . I just wanna say thanks for the writer and wish you all the best for coming!. Keto for weight loss

Avatar_small
lsm99 说:
2021年2月01日 00:46

If you set out to make me think today; mission accomplished! I really like your writing style and how you express your ideas. Thank you. ocean canvas paintings

Avatar_small
lsm99 说:
2021年2月02日 17:10

Thanks for sharing this quality information with us. I really enjoyed reading. Will surely going to share this URL with my friends. Boom 3D free download

Avatar_small
lsm99 说:
2021年2月07日 00:25

If you are looking for more information about flat rate locksmith Las Vegas check that right away. หวยฮานอยวันนี้

Avatar_small
lsm99 说:
2021年2月07日 18:54

I have a hard time describing my thoughts on content, but I really felt I should here. Your article is really great. I like the way you wrote this information. stool

Avatar_small
lsm99 说:
2021年2月10日 21:27

Thank you for another great article. Where else could anyone get that kind of information in such a perfect way of writing? I have a presentation next week, and I am on the look for such information. Karl Lagerfeld

Avatar_small
lsm99 说:
2021年2月10日 21:58

Cool stuff you have got and you keep update all of us. Emporio armani

Avatar_small
lsm99 说:
2021年2月11日 11:31

 really loved reading your blog. It was very well authored and easy to understand. Unlike other blogs I have read which are really not that good.Thanks alot! veterinary software

Avatar_small
lsm99 说:
2021年2月13日 22:10

Thank you for another great article. Where else could anyone get that kind of information in such a perfect way of writing? I have a presentation next week, and I am on the look for such information. relojes de plata para mujer

Avatar_small
lsm99 说:
2021年2月13日 23:47

you represent your views in this article. I agree with your way of thinking. Thank you for sharing. how to locate wifes phone without her knowing for free

Avatar_small
lsm99 说:
2021年2月17日 22:04

If you set out to make me think today; mission accomplished! I really like your writing style and how you express your ideas. Thank you. Buy Vicodin Online

Avatar_small
lsm99 说:
2021年2月26日 14:06

If you set out to make me think today; mission accomplished! I really like your writing style and how you express your ideas. Thank you. justcbd

Avatar_small
lsm99 说:
2021年3月01日 22:13

If you set out to make me think today; mission accomplished! I really like your writing style and how you express your ideas. Thank you. cbd oil bath bombs

Avatar_small
lsm99 说:
2021年3月15日 01:02

Hugo boss Hey, this day is too much good for me, since this time I am reading this enormous informative article here at my home. Thanks a lot for massive hard work.

Avatar_small
lsm99 说:
2021年3月29日 12:28

Wow, What a Excellent post. I really found this to much informatics. It is what i was searching for.I would like to suggest you that please keep sharing such type of info.Thanks https://buyersguide.ohsonline.com/company/277081/news/2296387/cpi-installs-regenerative-thermal-oxidizer-rto-at-bakery

Avatar_small
lsm99 说:
2021年4月04日 11:33

Mamoon es joyas de plata 925 real tienda online de moda del mundo, que ofrece compra y venta de plata, joyas de plata 925, joyas de plata y oro, mis joyas. cadenas

Avatar_small
lsm99 说:
2021年4月06日 20:03

Wow, What a Excellent post. I really found this to much informatics. It is what i was searching for.I would like to suggest you that please keep sharing such type of info.Thanks smm panels

Avatar_small
lsm99 说:
2021年4月14日 18:28

Excellent post. I was reviewing this blog continuously, and I am impressed! Extremely helpful information especially this page. Thank you and good luck. agen slot online

Avatar_small
lsm99 说:
2021年4月19日 22:45

Remarkable article, it is particularly useful! I quietly began in this, and I'm becoming more acquainted with it better! Delights, keep doing more and extra impressive! visit magnum 4d hari ini malaysia

Avatar_small
lsm99 说:
2021年4月22日 01:31

I read your blog frequently, and I just thought I’d say keep up the fantastic work! It is one of the most outstanding blogs in my opinion. best combat knife

Avatar_small
lsm99 说:
2021年4月22日 12:56

I am constantly surprised by the amount of information accessible on this subject. What you presented was well researched and well written to get your stand on this over to all your readers. Thanks a lot my dear. power generator solar

Avatar_small
lsm99 说:
2021年4月25日 00:49

Unit mix ranges from 1-4 Bedrooms and 4-Bedroom Villa and has a total of 638 residential units. Branded top notch appliances and fittings such as, Ernesttomeda, VZUG, Liebherr, Antonio Lupi, Axor & Hansgrohe, are being thoughtfully selected to ensure Leedon Green's exclusivity and premium. leedon green condo

Avatar_small
lsm99 说:
2021年5月04日 22:44

Pretty good post. I have just stumbled upon your blog and enjoyed reading your blog posts very much. I am looking for new posts to get more precious info. Big thanks for the useful info. Dy-Mi

Avatar_small
lsm99 说:
2021年5月21日 00:56

This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here keep up the good work Agen Slot Online

Avatar_small
lsm99 说:
2021年5月24日 00:08 For those who are nature and sports lover, they can enjoy the seamless connectivity of the trail at Seletar Park Connector which can lead to Punggol Coney Island. One can either jog or cycle to wind down after a hectic day to wind down or just enjoy a stroll with family after dinner. parc greenwichec
Avatar_small
lsm99 说:
2021年5月26日 11:38

For those who are nature and sports lover, they can enjoy the seamless connectivity of the trail at Seletar Park Connector which can lead to Punggol Coney Island. One can either jog or cycle to wind down after a hectic day to wind down or just enjoy a stroll with family after dinner. Parc Greenwich ec

Avatar_small
lsm99 说:
2021年5月27日 20:08

Good website! I truly love how it is easy on my eyes it is. I am wondering how I might be notified whenever a new post has been made. I have subscribed to your RSS which may do the trick? Have a great day! cannabis edibles

Avatar_small
lsm99 说:
2021年5月28日 19:36

Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post. smm instagram

Avatar_small
lsm99 说:
2021年6月14日 23:10

Its a great pleasure reading your post.Its full of information I am looking for and I love to post a comment that "The content of your post is awesome" Great work. Different forms of Pentobarbital available

Avatar_small
lsm99 说:
2021年7月07日 20:12

Its a great pleasure reading your post.Its full of information I am looking for and I love to post a comment that "The content of your post is awesome" Great work. Where to Buy Lortab Online

Avatar_small
ssali 说:
2022年9月26日 06:02

Great stuff. i am going to bookmark it, if you are looking for bluetooth fm transmitter, xiaomi redmi airdots, wifi versterker, beste wifi versterker, nokia 105, smartphone holder in Netherlands, get in touch with us.

 


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter