C++ References, Pointers, const

  C++, 技术


int ival = 1024;
int &refVal = ival; // refVal refers to ival

refVal is an alias(别名) of ival. Once it is defined, it cannot be bind to other variables. Changing refVal will also change ival.


Pointers can be defined, initialized and changed independently.

int ival = 42;
int *p; // *p defines a pointer
p = &ival; // initialized p to point to the object ival

pointer type should be the same as the object type!

When we have a pointer p, we can use * operator to access that project (*p)

void* Pointers

void* is a special pointer that holds an address, but the type of object is unknown

double obj = 3.14;
void *pv = &obj

const qualifier

const int bufSize = 512;

const pointers

A const pointer must be initialized, and once initiazlized, its value/address may not be changed

int errNumb = 0;
int *const curErr = &errNumb; // curErr will always point to errNumb

auto type

Let C++ decide which type it is, it must have an initializer

auto item = val1 + val2 // item initialized to the result of val1+val2

If val1 and val2 has the type of double, then item also has type double.