const修饰指针
char hello[] = "Hello";
char world[] = "World";
//无法修改p指向的内容如:p[0] = h;
//1.1)
const char* p = hello;
//1.2)
char const * p = hello;//第二种写法
//2)
//无法修改p的值如:p = world;
char* const p = hello;
//3)
//同时满足1)和 2)限制
const char* const p = hello;
//4)
//没有1)和 2)的限制
char* p = hello;
effective c++:
如果关键字const出现在星号左边,表示被指物是常量;
如果出现在星号右边,表示指针自身是常量;
如果出现在两边,表示被指物和指针两个都是常量;
我的记忆方式:
char* p = hello;//这是最不同的情况,如果这时在两边同时加个const
(const) char* p = (const) hello;//这就表明hello是个常量,不能去修改他
const修饰函数
class Rational {...};
//返回一个Rational常量,不能修改他的值
const Rational operator* {const Rational& lhs,
const Rational& rhs);
Rational a,b,c;
if( a* b = c) ... //报出错误
可以在一些情况避免 “==” 输入为 “=”的情况
什么时候调用const成员函数?
class TextBlock {
public:
//const对象调用
//第一个const说明返回值是const不能修改
//第二个const说明这个函数不应该改动类的值
const char& operator[](std::size_t position) const
{return text[position];}
char& operator[](std::size_t position)
{return text[position];} //非const对象调用
private:
std::string text;
};
如果真的需要改动在const成员函数的值,可以将在变量前加mutable如
...
mutable std::string text;
...
使用const来写非const函数
char& operator[](std::size_t position)
{return const_cast<char&>(//2)将返回结果去掉const修饰符
static_cast<const TextBlock&>(*this)//1)转化为const类型再调用[]操作符
[positioin]
);
}
再1)中如果不转换为const类型,将会递归调用非const函数,导致死循环
相反,使用非const函数来写const函数是不符合逻辑的