您的位置:首页 > 编程语言 > C语言/C++

Const in C++

2013-03-14 12:45 211 查看

Why const?Take a look at this snippet of codes
for(int i;i<512;i++){
cout<<i<<endl;
}


There is a problem with it. It is not evident diret from the codes what does the magic number 512 means. In addition to that, if this number appears 100 times in our program.80 times with this meaning and 20 times with another,how can we differ from them.So..

int memory=512;
for(int i;i<memory;i++){
cout<<i<<endl;
}


Now,the problems above are solved. But by doing so it takes a risk of the value of variable memory can be accidentially changed anywhere else in the program.So..

const int memory=512;
for(int i;i<memory;i++){
cout<<i<<endl;
}


We can define it with key word const to tell the compiler any assignment to this region of area which variable memory defined is not allowed.

Reference Const

Const reference is reference to const

Found an interesting thing, it is allowed
const int val1=10;
const int &val2=val1;
cout<<val1+1;  //output 11
return 0;


But not this one:

const int val1=10;
const int &val2=val1;
val1+=1;  //error
val2+=1;  //error
return 0;


It is logical that it is a const reference that may  refer to a const variable.

const int val1=10;
int &val2=val1; //error, an const int& expected


We can bind a const reference to a nonconst variable.An assignment from the side of nonconst is allowed, but from the side of const refecence is refused.

int val1=10;
const int &val2=val1; //allowed
val1+=1; // allowed
val2+=1; // error: assignment of read-only reference 'val2'


Const_iterator

iterator points to const element of the vector.

vector<int> v1(10,4);
for(vector<int>::const_iterator itr=v1.begin();itr!=v1.end();itr++){
*itr+=1;  //compiler error
cout<<*itr<<endl;
}


Iterator which is itself const

vector<int> v1(10,4);
for(const vector<int>::iterator itr=v1.begin();itr!=v1.end();){
*itr+=1;
cout<<*itr<<endl;break;
itr++;     //compile error
}

Pointers and Const Qualifier(Idiom: You can only tighten the access right of a variable as it is first defined)

const double pi=3.14;
double other=1;
const double *p=π   //pointer to const object pointed to const object,correct
p=&other;              //pointer to const object pointed to nonconst object,also correct
double *q;             //pointer to nonconst object
q=&other;              //correct, can only point to nonconst object
q=π                 //compile error, not const object


Const Pointer

const double pi=3.14;
double *const p=π         //pointer itself const
const double *const p=π   // const pointer points to const object

Pointers & Typedef

Cast On Const

const int i=5;
const_cast<int>(i)=2;/error: invalid use of const_cast with type 'int', which is not a pointer, reference, nor a pointer-to-data-member type


const int i=5;
int *k;
k=const_cast<int*>(&i);
*k=4;
cout<<*k;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: