下面的代码不能在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'为什么上面的语法可以被认为是非法的?
还没有在其他编译器上尝试过。
发布于 2015-02-19 03:05:50
编译器是正确的,所有符合的编译器都必须拒绝它。原因是声明的分组方式不同:
const TestList * p1将p1声明为指向常量TestList的指针。
const TestListPtr p2将p2声明为常量TestListPtr。TestListPtr是指向(非常数) TestList的指针。不带类型定义的p2拼写是这样的:
TestList * const p2 = p1;发布于 2015-02-19 03:28:33
这是语言语法不直观的一个地方。
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。
https://stackoverflow.com/questions/28591766
复制相似问题