const T* vs typedef

const T* vs typedef

本文关键字:typedef vs const      更新时间:2023-10-16

以下代码在visual studio 2012中无法为我编译:

//1. Define struct
struct TestList
{
...
};
//2 define a pointer to 1. struct as typedef
typedef TestList * TestListPtr;
//3. use it latter on in the code as follows:
    const TestList* p1 = 0;
    const TestListPtr p2 = p1;

然后,得到这个编译错误:

error C2440: 'initializing' : cannot convert from 'const TestList *' to 'const TestListPtr'

为什么以上内容可以被视为非法语法?

还没有在其他编译器中尝试过。

编译器是对的,所有符合要求的编译器都必须拒绝。原因是声明分组不同:

CCD_ 1将CCD_ 2声明为指向常量CCD_ 3的指针。

const TestListPtr p2声明p2为常数TestListPtrTestListPtr是指向(非常量)TestList的指针。在没有typedef的情况下拼写p2是这样的:

TestList * const p2 = p1;

这是一个语言语法不直观的地方。

int const i;

与相同

const int i;

当你混合指针时,有四种可能的选择:

int* p1;               // You can modify both p1 and *p1
int const* p2;         // You can modify p2 but not *p2
int* const p3;         // You can not modify p3 but can modify *p3
int const* const p3;   // You can not modify p4 or *p4

不幸的是,你可以写

int const* p2;

作为

const int* p2;

这也是你困惑的根源。

而不是使用

const TestListPtr p2 = p1;

如果你使用

TestListPtr const p2 = p1;

很清楚CCD_ 10的哪一部分是恒定的。显然const TestList * p11不能被修改,但是*p2可以被修改。