c++ - 如何在 C++ 中的 const 覆盖函数中调用非 const 函数

标签 c++ overriding call constants

<分区>

下面有一个类

class A
{
    public:
        string& getStr()
        {
          // Do a lot of work to get str
          return str
        }
        const string& getStr() const;
};

我可以在第二个函数中调用第一个函数吗?我想这样做,因为第二个函数与第一个函数有很多共同的代码。不能这样:

const string& A::getStr() const
{
    // Wrong
    A temp;
    return temp.getStr();
}

因为增加了一个新的temp,*this和temp之间的内部状态是不同的(*this != temp)。

可以像我描述的那样调用吗?

最佳答案

How do I remove code duplication between similar const and non-const member functions? 中所述,避免代码重复的解决方案是将逻辑放在 const 方法中(假设您不需要修改对象状态或您修改的成员是可变的)并从非 const 方法调用 const 方法:

class A
{
    public:
      string& getStr()
      {
            return const_cast<string&>( static_cast<const A *>( this )->getStr() );
      }

      const string& getStr() const {
        // Do a lot of work to get str
        return str
      }
};

关于c++ - 如何在 C++ 中的 const 覆盖函数中调用非 const 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19162737/

相关文章:

c++ - 对数时间聚合的数量

java - 在重写 equals 方法期间存储中间结果

css - 如何在子主题中覆盖简单的数字下载 css 文件?

arrays - 将在第一个函数中创建的数组传递给第二个函数

java - 什么时候调用静态{}?

c++ - 访问 vector 的内容

c++ - 使用 CMake 在 Windows 上设置 FLTK

java - Java中的动态多态性和静态多态性有什么区别?

asp.net - 调用 en 外部 javascript 文件的函数

c++ - 如何在多线程中安全地使用 boost deadline timer?