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

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[]
//可以对一个常量对象进行读操作,但不能进行写操作

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: