|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
More on const
const is tricky enough that it deserves some study.
Unlike C, in C++ constreally is constant. The following
declarations work in C++ but not in C:
|
|
|
|
|
|
|
|
const int maxn = 1000;
int a[maxn + 1];
|
|
|
//#define maxn 1000
|
|
|
|
|
|
|
|
|
When pointers and const are involved in the same
declaration, what does it mean? Does it mean the pointer
doesn't change (const pointer)? Does it mean the thing the
pointer points at doesn't change (pointer to const)? Or does
it mean neither the pointer nor the thing it points at can
change? Not so clear, but luckily, it is possible to express
all three concepts in C++:
|
|
|
|
|
int i = 1, j = 3;
int* const p = &i;
const int* q = &i;
const int* const r = &i;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// const pointer
// pointer to const
// const pointer to const
|
|
|
|
*p = 5;
p = &j;
*q = 5;
q = &j;
*r = 5;
r = &j;
|
|
// okay
// error, p is read-only pointer
// error, thing pointed to by q?
// okay
// error, like *q = 5
// error,
|
|
|
|
|
|
|
|
|
|
|
const reference variables
You can have a reference to an object, yet tell the compiler
you don't want use of this reference to change the variable.
|
|
|
|
|
|
22-Mar-98
|
|
|
|
Page 10
|
|
|
|
C201/TAM
|
|
|
|
|