2011-09-05 69 views
3

我无法解释自己以下代码:关于C++中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上运行)

+3

请阅读:http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.5 –

回答

10

double* const类型是一个指向非const double的const指针。如果你想要一个指向const double的指针,你必须使用double const*(或者如果你想要一个const指针指向一个const double,则使用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 
+1

这意味着他需要使用'double const * const',对吧? – wormsparty

+0

@wormsparty:他不需要,不。 'double const * p2 = &d1;'很好。 'p'和'p1'的定义中的'const'防止它们在后来被更改为包含不同的地址,所以如果他需要的话,除了需要能够指向'const double',例如'd1',那么他需要'double const * const'。 –

+0

因为d1是一个const int,所以它会这样做:const double * p1 = &d1; – Gob00st

4

double * const p1的声明const指针非constdouble,即指针可以改变(即它可以重新尖),但没有的事它指向的是。但是d1const

你的意思是:

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

[见从C++ FAQ this question]

+0

我建议编写'double const *'。它等同于'const double *',但是你可以用简单的规则“const应用于它前面的所有内容”而不需要额外的规则。“const在开头适用于最内层的类型”。 –

+0

@Jan:我看到你的逻辑,但最终它是个人偏好。我读了上面的定义,“p是一个指向const double的指针”;对我而言,这并不令人困惑。 –

+1

@Jan:就我个人而言,我认为以您的方式教授它的一个主要好处是编写'const'首先诱使人们认为'typedef char * cptr; typedef const cptr ccptr;'与'typedef const char * ccptr;'相同。他们不太可能认为,如果他们一直写'typedef char const * ccptr;'。即便如此,我还是倾向于写出奥利赋予自由的方式,并且在相关新闻中,也写'const int i = 0;'而不是'int const i = 0;'。 –

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 
0

你可以很容易理解的代码以下列方式。

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

这里在第2行,问题是我们正在给常量值赋予一个常量值d1,这个常量值可以在将来改变。

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

在我们的例子中,右侧的数据类型可以被当作是指向const double的指针,其中左侧是一个指向double的指针,这个指针相反并且引发了一个compilor错误。