ipk*_*iss 3 c++ pointers const
我无法解释自己以下代码:
double d = 100;
double const d1 = 30;
double* const p = &d; // Line 1
double* const p1 = &d1; // Line 2
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,没问题Line 1,但Line 2产生错误:
"error C2440: 'initializing' : cannot convert from 'const double *__w64 ' to 'double *const '"
Run Code Online (Sandbox Code Playgroud)
有人可以详细说明吗?(我使用的是VS C++ 2005,在Win XP SP3上运行)
Syl*_*sne 11
该类型double* const是一个指向非const double的const指针.如果你想要一个指向const double的指针,你必须使用double const*(或者double const* const你想要一个指向const double的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
Run Code Online (Sandbox Code Playgroud)