C++中const 的用法
2017-03-02 13:30
176 查看
/* //条款03:尽可能使用const //常量指针 char greeting[] = "Hello"; char *p1 = greeting; //既不是常量指针,也不是常量数据 const char *p2 = greeting; //数据不是常量(可更改),但指针所指地址不可更改 char *const p3 = greeting; //数据是常量(不可更改),但指针所指地址可以更改 const char *const p4 = greeting; //数据是常量(不可更改),指针所指地址也不可以更改 //函数参数传递 void f1(const Widget *pw); //f1获得一个指针,指向一个常量的(不变的)Widget对象 void f2(Widght const *pw); //同上 //vector 迭代器 std::vector<int> vec; const std::vector<int>::iterator iter = vec.begin(); //像 T* const *iter = 10; //编译器不会报错,因为左值可更改 ++iter; //编译器报错,iter是一个const(不可更改) std::vector<int>::const_iterator Citer = vec.begin(); *Citer = 10; //报错,因为Citer所指对象为一个常量 Citer++; //正确 //const 成员函数 class Text{ public: Text(const std::string& text) :text(text){}; ~Text(){}; const char& operator[](std::size_t position)const{ return text[position]; } char &operator[](std::size_t position){ return text[position]; } private: std::string text; }; Text tx("hello world"); std::cout << tx[2] << std::endl; //调用non—const Text::operator[] tx[2] = 'x'; //可以进行写操作, //注意:这里能进行写操作是因为[]操作返回的是一个对char的引用, //而不单单是一个char,若只是返回一个char ,则 tx[2] = 'x' 无法通过编译 Text ctx("hello world"); ctx[2] = 'x'; //错误,不能写一个const std::cout << ctx[2] << std::endl;//调用const Text::operator[] //可以对一个常量对象进行读操作,但不能进行写操作 */
相关文章推荐
- C++关键字const用法详解
- c++中const的用法详解
- C++中const的用法汇总
- C++中CONST的用法
- C++的const用法
- C++中const 的用法
- C++之 const的用法
- C++中const的用法详解
- C/C++中const用法小结
- C++中const用法浅析
- c++中const的用法详解
- C++ const用法总结
- [转]C/C++中关键字static,const,inline,define,typedef的用法及其意义
- C++中const的用法详解
- [c++学习]const用法总结篇
- 重新拾起c++中const得用法;
- 高质量C++(const用法)
- C++中 Const用法小结(转载)
- C++中const用法总结
- C++中const用法总结