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

C++中关于const, reference(&)一点小结

2013-08-12 21:18 387 查看
自己看C++ Primer做的小结,因为是初学者,可能不够全面,欢迎批评指正,谢谢

两个原则:const常量定义时必须初始化; reference (&) 引用定义时必须初始化

...

int x;

...

int const a = x; const int a = x; //二者等价

int const *p; const int *p; //二者等价, p是指向const型的int

int *const p = &x; //const常量必须初始化

const vector::iterator iter = it_x; //const型的普通迭代器, iter本身是const, 必须初始化, iter指向的值可变

iter = it_y; // error: 不能给const变量(常量)iter重新赋值

*iter = some value; // ok: 给普通iterator解引用赋值

vector::const_iterator const_it; //const迭代器, 可以改变const_it所指向的对象, 但不能改变所指向的对象的值

const_it = it_y; // ok: 给非const变量const_it重新赋值

*const_it = some value; // error: 不能给const迭代器的解引用赋值

const vector::const_iterator it = it_x; //const型的const迭代器, 必须初始化, it本身的值和所指向的对象的值都不能改变

it = it_y; // error: 不能给const变量(常量)it重新赋值

*it = some value; // error: 不能给const迭代器的解引用赋值
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: