#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 !
constapplies to the thing to the left, unless there is nothing to the left in which case it applies to the thing on the right. (Yes, this is unnecessarily confusing and silly.)constin the end means no change will be made to the object/class.