• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

Dean@cnbolg

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

const成员函数

effective C++ 03 - 多才多艺的const

const成员函数

  类的非const对象既可以访问const成员函数,又可以访问非const成员函数。

  类的const对象则只能访问类的const成员函数,不能访问非const成员函数。

  因此,当需要使用类的const对象时,一般就需要为其设计相应的const成员函数。

  在设计const成员函数时,应尽量设计为logical constness(编译器只能发现bitwise/physical  constness),即在逻辑上避免指针所指之物被修改等。

  P.S. 如果声明变量为mutable(可变的),那么在const成员函数内修改其值是允许的。

  栗子:

#include <string>


class ConstMember
{
public:
    explicit ConstMember(std::string str);

    char& operator [] (std::size_t position);

    const char& operator [] (std::size_t position) const; // const成员函数. 只改变常量性(constness)也是重载!

private:
    std::string m_str;
};

  当成员函数有const和非const两个重载版本时,应让非const的成员函数调用const的成员函数,以实现代码复用。

  相反,任何时候都不要让const成员函数调用非const版本的重载!这有悖与我们设计const成员函数的初衷!

类的实现如下:

char& ConstMember::operator [] (std::size_t position)
{
    return  const_cast<char&>(                                         //2. cast away the return valus's constness
        static_cast<const ConstMember&>(*this)[position]  //1. cast to const to revoke the "const op[]"
    );
}

const char& ConstMember::operator[] (std::size_t position) const
{
    if(position < 0 || position > m_str.length())
        return NULL;

    //... do
    //... other
    //... things

    return this->m_str[position];


    /* DON'T DO THIS */
    //return const_cast<ConstMember&>(*this)[position];  // run OK - casting away constness
    //return static_cast<const ConstMember>(*this)[position];  // run OK - casting return value to const.
    //return static_cast<const ConstMember&>(*this)[position];  // X - self recursive
}

const 迭代器

  待续。。。

 

posted on 2017-03-12 22:50  Dean@cnbolg  阅读(180)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3