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 like a hit:
const int * p = & i1;
This means that the "p" points cannot be changed, but p cannot be changed, right? so
p = & i2;
this line can be executed, yes?
This line:
int const *p2 = &i1;
In my opinion, this means that p2 cannot be changed, while p2-points can be changed, right? Why
p2 = & i2;
can be compiled?
About this line:
const int const * p3 = & i1;
p3 = & i2;
Oh god ... I'm crazy. I do not know why this line can be compiled without errors ... Can someone help me?
Another code that 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 can this code be compiled? AT
int const * getP () const
* p!
.
- , , .
- , , .
, : int const * ptr int const * ptr, . , -
const int num = 5; // Both mean the same.
int const num = 5;
To, , , , int* const. , .
int num = 5;
int* const ptr; // Wrong
ptr = # // Wrong
int* const ptr = #
*ptr = 100;
. , , . (.. const int * const)
, , . , .
const int const *p3 = &i1;
p3 = &i2; // Wrong
p3 . , .
const - , . *p = 1;, . p . -
int const * Coo2::getP() const
{
*p = 1; // State of `p` is still not modified.
p = new int ; // Error: Changing the memory location to which p points.
// This is what changing the state of object mean and
// is not allowed because of `const` keyword at the end of function
return this->p;
}
, , :)
4 :
int * w;, w . , . w , :int * w = &a;
:w = &b;()*w = 1;()int * const x;
, x , . x , :int * const x = &a;
:x = &b;(wrong), x .
:*x = 1;(true), x .int const * y;// |const int * y;
, y , . y , :int const * y = &a;
:y=&b;(true), y - , .
:*y=1;(wrong), , y , .int const * const z;// |const int * const z;
, z , . z , :int const * const z = &a;
, :z = &b;(wrong)*z = 1;(wrong)
; / int ;
int main() {
int a,b;
int* w; // read/write int, read/write pointer
w= &b; // good
*w= 1; // good
int* const x = &a; // read only pointer, read/write int
// x = &b; // compilation error
*x = 0; // good
int const * y; // read/write ptr, read only int
const int * y2; // " " "
y = &a; // good
// *y = 0; // compilation error
y2 = &a; // good
// *y2 = 0; // compilation error
int const * const z = &a; // read only ptr and read only int
const int * const z2 = &b; // " " " "
// *z = 0; // compilation error
// z = &a; // compilation error
// *z2 = 0; // compilation error
// z2 = &a; // compilation error
}