首页 > 编程语言 > 详细

c++之const成员函数强制调用非const成员函数

时间:2020-05-27 22:38:34      阅读:61      评论:0      收藏:0      [点我收藏+]

我们都知道const成员函数只能调用非const成员函数

但是有的时候,我们为了代码复用
例如:
    T operator[](int i) const;
    T& operator[](int i);

为了实现const和非const两个版本,我们选择使用重载,但是里面的内容可能是相同的,为了代码复用可以:

    T& operator[](int i) {
        if( (i >= 0) && (i < m_length) ) {
            return m_array[i];
        }
        else {
            THROW_EXCEPTION(IndexOutOfBoundsException, "T& operator[](int i) i");
        }
    }
    T operator[](int i) const{
        return const_cast<SeqList&>(*this)[i];
    }

使用 const_cast<SeqList&>(this),把const版本的this转化为非const然后调用非const版本的[],因为const只在编译期,在运行期是不存在const的

c++之const成员函数强制调用非const成员函数

原文:https://www.cnblogs.com/zero-waring/p/12976851.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!