c++ - const 指针和指向 const 的指针

标签 c++ pointers

不要这样做:

int* const p;

还有这个:

const int* p;

你不能通过这样做来使其更容易阅读吗:

typedef int* ptr;
const ptr p; //Constant pointer to an integer

还有:

typedef const int ptr;
ptr* p; //Pointer to a constant integer

最佳答案

确实没有理由这样做。它不仅会降低代码的可读性,而且没有任何意义。

typedef const int ptr;

^ 这没有任何意义 - 它是一个 const int 但你称它为指针。 只要保护你自己和读者并输入即可

const int* ptr;

编辑:

直接回答您的问题:不,您不会让事情变得更容易。

编辑#2

还有一点,当你有时会发生什么

typedef const int ptr;
typedef const long ptr;
typedef const float ptr;

这不仅没有意义,因为它们不是指针,而且现在你有一堆叫做 ptr 的东西,你会对你实际写的内容感到困惑。

关于c++ - const 指针和指向 const 的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18200343/

相关文章:

c++ - 创建窗口不起作用但没有给出错误消息

c++ - MSVC 中的复合文字

c++ boost::iterator_range<iter> string_view 错误

c++ - 创建一个 const char* const* 数组

c++ - 如何使用指针数组反转数据(解析二进制文件)

c++ - 理解C++中指针的操作

c++ - N 个 child 向 parent 发送消息

c++ - 在范围外丢失指针引用

arrays - 修复char格式错误-Linux系统C程序

c - 使用带有数组的 `addres of` 运算符作为指针的初始值设定项时收到警告