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

时间:2011-09-05 14:06:05

标签: c++ pointers const

我无法解释以下代码:

   double d = 100;

    double const d1 = 30;

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

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

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

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

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:4)

double * const p1声明指向非const const的{​​{1}}指针,即指针可以更改(即可以重新指向),但不是它指向的东西。但doubled1

你的意思是:

const

[另请参阅C ++ FAQ中的this question。]

答案 2 :(得分:2)

如果您从右到左阅读声明会更容易:

double const *       p; // pointer to const double
const double *       p; // pointer to const double
double       * const p; // const pointer to double
double const * const p; // const pointer to const double

答案 3 :(得分:0)

您可以通过以下方式轻松理解代码。

double const d1 = 30;
double* const p1 = &d1;

在第2行中,问题是我们将const值d1赋值给非const值,以后可以更改。

如果我们将右侧值的数据类型理解为左侧值,将会更容易。

在我们的例子中,右侧数据类型可以被视为指向const double的指针,其中左侧是指向double的指针,这与之相矛盾并且抛出了compilor错误。

相关问题