Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4463486
  • 博文数量: 356
  • 博客积分: 10458
  • 博客等级: 上将
  • 技术积分: 4734
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-24 14:59
文章分类

全部博文(356)

文章存档

2020年(17)

2019年(9)

2018年(26)

2017年(5)

2016年(11)

2015年(20)

2014年(2)

2013年(17)

2012年(15)

2011年(4)

2010年(7)

2009年(14)

2008年(209)

分类: C/C++

2008-05-17 17:51:20

在论坛上碰到有人问
类中成员函数 当const与non-const成员函数里的代码重复时,怎么只实现一个,而让另一个调用它.
为什么const不能调用 non-const
这就要翻翻effective c++这本书了
原书代码如下
 
class TextBlock
{
public:
   
const char& operator[](std::size_t position)const
    {
        ...
        ...
        ...
       
return text[position];
    }
   
char& operator[](std::size_t position)
    {
       
return const_cast<char&>(static_cast<const TextBlock&>(*this)[position]);
    }
private:
    std::
string text;
};
static_cast (*this)这里面把*this从TextBlock&类型转换成const TextBlock&这样调用
(变成了常对象了,其调用的是const成员函数),因为返回的也是const,所以前面const_cast 把返回值的const移除了.这样这个对象noconst成员函数也能操作了.
其实书上说的很详细
 
那为什么const不能调用 non-const呢
常成员函数 
使用const关键字进行说明的成员函数,称为常成员函数。一般情况下,只有常成员函数才有资格操作常成员变量或常对象,没有使用const关键字说明的成员函数不能用来操作常对象  
通过const_cast虽然能使non-const成员函数 达到操作常成员对象或者常对象  但那是极度危险的,const成员函数承诺绝不改变其对象的逻辑状态, const函数直接调用non-const函数 那说明你const函数无法保证只读不写 这显然与意图违背, 你违背了你的承诺. 

 
 
阅读(2107) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~