const笔记

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函数是不符合逻辑的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值