我无法解释以下代码:
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/