c++ - 使用类型别名不适用于 "const"指针

标签 c++ c++11 pointers constants using

这里,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/

相关文章:

c++ - 如何为跨平台 C++ 开发设置 Visual Studio

c++ - 以最新优先格式显示日志数据

c++ - QByteArray 的标准替代品

c - 如何使用 C 中的指针将数组 (1D) 传递给函数?

C++ 共同祖先问题。它是什么?

c++ - "Link executables with xxx.lib"是什么意思

c++ - C++11 auto 关键字太多了?

c++ - 排序函数如何作用于一对整数对的 vector ?

c - 打印的是垃圾值吗?

c++ - 无法将参数从 int * 转换为 const int *&