首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >const T* vs typedef

const T* vs typedef
EN

Stack Overflow用户
提问于 2015-02-19 03:02:47
回答 2查看 129关注 0票数 3

下面的代码不能在visual studio 2012中为我编译:

代码语言:javascript
复制
//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;

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

代码语言:javascript
复制
error C2440: 'initializing' : cannot convert from 'const TestList *' to 'const TestListPtr'

为什么上面的语法可以被认为是非法的?

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

EN

回答 2

Stack Overflow用户

发布于 2015-02-19 03:05:50

编译器是正确的,所有符合的编译器都必须拒绝它。原因是声明的分组方式不同:

const TestList * p1p1声明为指向常量TestList的指针。

const TestListPtr p2p2声明为常量TestListPtrTestListPtr是指向(非常数) TestList的指针。不带类型定义的p2拼写是这样的:

代码语言:javascript
复制
TestList * const p2 = p1;
票数 7
EN

Stack Overflow用户

发布于 2015-02-19 03:28:33

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

代码语言:javascript
复制
int const i;

等同于

代码语言:javascript
复制
const int i;

当您混合指针时,有四个可能的选项:

代码语言:javascript
复制
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

不幸的是,您可以编写

代码语言:javascript
复制
int const* p2;

作为

代码语言:javascript
复制
const int* p2;

另外,这也是你困惑的根源。

不是使用

代码语言:javascript
复制
const TestListPtr p2 = p1;

如果您使用

代码语言:javascript
复制
TestListPtr const p2 = p1;

很明显,p2的哪一部分是常量。很明显,不能修改p2,但可以修改*p2

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28591766

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档