Wednesday, 28 June 2017

const

Notes for reading C++ Primer 4/e.

const Reference

Reference to a constant object.
const int ival = 1024;
const int &refVal = ival;
const int &r = 42;
const int &r2 = r + 3;


const_iterator

for (vector<string>::const_iterator iter = text.begin();
iter != text.end(); ++iter) {
    *iter = " ";  // error: *iter is const
}
vector<int> nums(10);
const vector<int>::iterator cit = nums.begin();
*cit = 1;  // OK
++cit;  // error: cit is const


Pointers & const

Pointers to const

const double pi = 3.14;
double *ptr = &pi;  // error: nonconst pointer
const double *cptr = &pi;  // OK

double dval = 2.99;
cptr = &dval;  // OK

const Pointer

int errNumber = 0;
int *const curErr = &errNumber;
curErr = curErr;  // error: curErr is const

if (*curErr) {
    errorHandler();
    *curErr = 0;  // OK
}

const Pointer Point To A const Object

const double pi = 3.14159;
const double *const pi_ptr = &pi;
pi_ptr is a constant pointer, point to a const double object.


Pointers & Typedefs

typedef string *pstring;
const pstring cstr;
Q: What is cstr?
A: Constant point, point to string.

No comments:

Post a Comment