有关C ++中的const指针的问题吗? [英] Question about const pointer in C++?
问题描述
我无法为自己解释以下代码:
I cannot explain myself the following code:
double d = 100;
double const d1 = 30;
double* const p = &d; // Line 1
double* const p1 = &d1; // Line 2
在上面的代码中,Line 1
可以,但是Line 2
会产生错误:
In the above code, Line 1
is ok, but Line 2
produces the error:
"error C2440: 'initializing' : cannot convert from 'const double *__w64 ' to 'double *const '"
有人可以详细说明吗? (我使用的是在Win XP SP3上运行的VS C ++ 2005)
Can anyone elaborate on that, please? (I am using VS C++ 2005, running on Win XP SP3)
推荐答案
类型double* const
是指向非const double的const指针.如果要使用指向const double的指针,则必须使用double const*
(如果要使用指向const double的const指针,则必须使用double const* const
).
The type double* const
is a const pointer to a non-const double. If you want a pointer to a const double, you have to use double const*
(or double const* const
if you want a const pointer to a const double).
在C ++中,使用指向double的简单指针,您既可以获取指针本身的常量(即,可以使其指向另一个位置)又可以是值的常量(可以更改值)吗?通过指针)可以独立配置.这为您提供了四个非常相似但不兼容的类型:
In C++, with a simple pointer to a double, you the const-ness of both the pointer itself (ie, can you make it point at another location) and the const-ness of the value (can you change the value through the pointer) can be configured independently. This gives you four very similar, but incompatibles types:
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 ++中的const指针的问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!