这里,const
指针保存着const
变量的地址。喜欢:
#include <iostream>
int main()
{
const int i = 5;
const int* ptr = &i;
}
它工作正常。
但是,如果我使用 using (Type alias)喜欢:
#include <iostream>
using intptr = int*;
int main() {
const int i = 5;
const intptr ptr = &i;
}
GCC 编译器报错。 [Live demo]
为什么指针不适用于 using
类型别名?
最佳答案
const intptr ptr
等同于 int * const ptr
- const pointer to non-const int,而不是 const int * ptr
-指向 const int 的非常量指针。
如果您发现指针声明的这种从右到左的阅读顺序令人困惑,您可以使用 Straight declarations提供别名模板以从左到右阅读顺序声明指针类型的库:
const ptr<int> p; // const pointer to non-const int
ptr<const int> p; // non-const pointer to const int
关于c++ - 使用类型别名不适用于 "const"指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47261351/