about “int const *p” and “const int *p ”

#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{
    int i1 = 0;
    int i2 = 10;

    const int *p = &i1;
    int const *p2 = &i1;
    const int const *p3 = &i1;

    p = &i2;
    p2 = &i2;
    p3 = &i2;

    cout << *p << endl
        << *p2 <<endl
        << *p3 <<endl;
    return 0;
}

The code can be compiled with both VC6.0 and VC2010. But I have questions as blow:

const int *p = &i1;

It means what the "p" points can not be modified,but p can not be modified,am I right? so

p = &i2;

this line can be complied,yes?

This line:

int const *p2 = &i1;

In my mind,this means p2 can not be modified while what p2 points can be changed, am i right? Why the

p2 = &i2;

can be compiled?

About this line:

const int const *p3 = &i1;

p3 = &i2;

Oh,god... I am crazy. I have no idea why this line can be compiled with no error... Can any body help me?

Another code which confused me is here:

class Coo2    
{      
 public:     

 Coo2() : p(new int(0)) {}    

 ~Coo2() {delete p;}    


    int const * getP() const   
    {      
         *p = 1;         
         return this->p;      
    }      

 private:    
      int* p;    
};   

why this code can be compiled? In

int const * getP() const

I have change the value or *p !

8
задан Jacob 26 September 2012 в 02:06
поделиться