c++ - 关于 C++ 中的 const 指针的问题?

标签 c++ pointers constants

我无法解释以下代码:

   double d = 100;

    double const d1 = 30;

    double* const p = &d; // Line 1
    double* const p1 = &d1; // Line 2

在上面的代码中,第 1 行 没问题,但是 第 2 行 产生了错误:

"error C2440: 'initializing' : cannot convert from 'const double *__w64 ' to 'double *const '"

有人可以详细说明一下吗? (我使用的是 VS C++ 2005,在 Win XP SP3 上运行)

最佳答案

double* const 类型是指向非常量 double 的常量指针。如果你想要一个指向 const double 的指针,你必须使用 double const*(如果你想要一个指向 const double 的 const 指针,则必须使用 double const* const)。

在 C++ 中,对于一个简单的 double 指针,您可以同时了解指针本身的常量性(即,您能否使其指向另一个位置)和值的常量性(您能否更改该值通过指针)可以独立配置。这为您提供了四种非常相似但不兼容的类型:

double const* const p1; // Const pointer to const double
                        //  . you can't have the pointer point to another address
                        //  . you can't mutate the value through the pointer

double const* p2;       // Non-const pointer to const double
                        //  . you can have the pointer point to another address
                        //  . you can't mutate the value through the pointer

double* const p3;       // Const pointer to double
                        //  . you can't have the pointer point to another address
                        //  . you can mutate the value through the pointer

double* p4;             // Non-const pointer to non-const double
                        //  . you can have the pointer point to another address
                        //  . you can mutate the value through the pointer

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

相关文章:

C 使用指针从矩阵中提取数组

java - C# out IntPtr 在 Java 中等效

pointers - 如何在MQL中分配指向结构数组的指针?

C# 字符串常量与静态属性

c - 指向数组类型的指针,或者添加 "array decay to pointer"、 "typedef"、 "const"和 "*"时 "&"发生了什么

c++ - 如何使用c++生成不相关的随机序列

使用 externalNativeBuild.ndkBuild 编译的 Android native 调试

c++ - 将 boost::optional 左值作为对函数的引用传递

c++ - 如何在 OpenCV 中对视频文件中物体不移动的所有帧进行平均?

c - 非常大的 C 结构的分段初始化