【问题标题】:const member functions can call const member functions only?const 成员函数只能调用 const 成员函数吗?
【发布时间】:2011-06-04 14:37:00
【问题描述】:

const 成员函数是否只调用 const 成员函数?

class Transmitter{
  const static string msg;
  mutable int size;
  public: 
    void xmit() const{
    size = compute();
    cout<<msg;
  }
  private:
   int compute() const{return 5;}
};

 string const Transmitter::msg = "beep";

 int main(){
   Transmitter t;
   t.xmit();
   return EXIT_SUCCESS;
 }

如果我不将 compute() 设为 const,则编译器会抱怨。 是不是因为一个 const 成员函数不允许修改成员,它不会允许 任何对非常量的调用,因为这意味着 const 成员函数将“间接”修改数据成员?

【问题讨论】:

    标签: c++ const-method


    【解决方案1】:

    是不是因为 const 成员函数不允许修改成员,所以它不允许任何对非 const 的调用,因为这意味着 const 成员函数将“间接”修改数据成员?

    是的。

    【讨论】:

      【解决方案2】:

      是的:const 成员函数只能看到类的const 版本,这意味着编译器不会在const 成员函数中找到任何非const 成员(数据或函数)。

      此效果传播到类的 const 对象(实例),其中只有 const 成员可以访问。

      如果应用正确,const 将允许程序员检查他对类的使用,并确保没有对任何不应更改的对象进行不必要的更改。

      【讨论】:

        【解决方案3】:

        是的。当你调用 'xmit()' 时,它的 'this' 指针将是 const,这意味着你不能从那里调用非 const 方法,因此 'compute()' 必须是 const

        【讨论】:

          【解决方案4】:

          正如其他人所说;是的。

          如果您出于特殊原因希望计算为非 const,例如,如果它使用一些本地缓存来存储计算,那么您仍然可以通过声明 const 版本从声明为 const 的其他函数调用它

            private:
                 int compute() const{return ( const_cast<Transmitter*>(this)->compute());}
                 int compute() {return 5;}
          

          【讨论】:

          • 对此更好的解决方案是将缓存声明为可变的,以明确声明它允许在 const 操作期间更改。
          • 对于简单的缓存,我同意,但对于涉及其他功能的更复杂的功能,这是一项值得了解的成熟技术
          【解决方案5】:

          你的断言和分析都是正确的。

          【讨论】:

            猜你喜欢
            • 2016-08-17
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-03-14
            • 2013-05-17
            • 1970-01-01
            • 2021-05-20
            • 1970-01-01
            相关资源
            最近更新 更多