问题描述
此处, 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";指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!