以下代码在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'
上述原因可以被认为是非法语法?
尚未尝试过其他编译器。
答案 0 :(得分:7)
编译器是对的,所有符合条件的编译器都必须拒绝它。原因是声明组的区别不同:
const TestList * p1
声明p1
是指向常量TestList
的指针。
const TestListPtr p2
声明p2
为常数TestListPtr
。 TestListPtr
是指向(非常数)TestList
的指针。在没有typedef的情况下拼出p2
是:
TestList * const p2 = p1;
答案 1 :(得分:1)
这是语言语法不直观的地方。
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;
很清楚p2
的哪一部分是不变的。很明显p2
无法修改*p2
。