使用类型别名不适用于"const";指针 [英] using type alias doesn't work with "const" pointer

查看:64
本文介绍了使用类型别名不适用于"const";指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处, const 指针保存 const 变量的地址.就像:

Here, const pointer hold the address of const variable. like :

#include <iostream>

int main() 
{    
    const int i = 5;
    const int* ptr = &i;
}

一切正常.

但是,如果我使用使用(类型别名),例如:

But, If I use using (Type alias) like:

#include <iostream>

using intptr = int*;

int main() {    
    const int i = 5;
    const intptr ptr = &i;
}

GCC编译器给出错误. [实时演示]

GCC compiler gives an error. [Live demo]

为什么使用类型别名,指针不能与一起使用?

Why pointer does not work with using Type alias?

推荐答案

const intptr ptr 等效于 int * const ptr -指向非const int的const指针,而不是 const int * ptr -指向const int的非const指针.

const intptr ptr is an equivalent of int * const ptr - const pointer to non-const int, not const int * ptr - non-const pointer to const int.

如果您发现指针声明的这种从右到左的阅读顺序令人困惑,则可以利用

If you find such right-to-left reading order for pointer declarations confusing you can utilize Straight declarations library which supplies alias templates to declare pointer types with left-to-right reading order:

const ptr<int> p; // const pointer to non-const int
ptr<const int> p; // non-const pointer to const int

这篇关于使用类型别名不适用于"const";指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆