的typedef指针常量的怪事 [英] typedef pointer const weirdness
本文介绍了的typedef指针常量的怪事的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑以下code:
typedef struct Person* PersonRef;
struct Person {
int age;
};
const PersonRef person = NULL;
void changePerson(PersonRef newPerson) {
person = newPerson;
}
由于某些原因,编译comlaining有关只读值不可转让。但const关键字不应使指针常量。任何想法?
For some reason, the compiler is comlaining about read-only value not assignable. But the const keyword should not make the pointer const. Any ideas?
推荐答案
注意
typedef int* intptr;
const intptr x;
是不一样的:
const int* x;
的IntPtr
是指向int的指针。 常量的IntPtr
是恒定指向 INT
,不是指针恒 INT
。
intptr
is pointer to int. const intptr
is constant pointer to int
, not pointer to constant int
.
所以,一个typedef指针后,我不能让它常量的内容了吗?
so, after a typedef pointer, i can't make it const to the content anymore?
有一些丑陋的方式,比如gcc的的typeof宏观:
There are some ugly ways, such as gcc's typeof macro:
typedef int* intptr;
intptr dummy;
const typeof(*dummy) *x;
但是,正如你看到的,这是毫无意义的,如果你知道的IntPtr 背后的类型。
but, as you see, it's pointless if you know the type behind intptr
.
这篇关于的typedef指针常量的怪事的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文