繁体   English   中英

const成员函数只能调用const成员函数吗?

[英]const member functions can call const member functions only?

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的调用,因为这意味着const成员函数将“间接”修改数据成员?

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

是。

是的: const成员函数仅查看该类的const版本,这意味着编译器将在const成员函数内找不到任何非const成员(数据或函数)。

此影响传播到该类的const对象(实例),在该对象中只能访问const成员。

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

是。 当您调用'xmit()'时,其'this'指针将为const,这意味着您无法再从那里调用非const方法,因此'compute()'必须为const

正如其他人所说的; 是。

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

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

您的主张和分析都是正确的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM