【问题标题】:Constness of version method when it gets called by another method in the same class同一类中的另一个方法调用版本方法时的常量
【发布时间】:2017-03-12 20:46:26
【问题描述】:

我知道当一个方法同时存在具有相同名称和参数的 const 和非 const 版本时,选择的版本由 *this 的 const-ness 决定。 (方法的常量是签名的一部分吗?)

但是当它被另一个方法调用时会发生什么?

一个例子

class a{
   void b() const{
      c();
      //do fantastic things
   }
   const_iterator c() const;
   iterator c();
};

当我从 a 的非常量实例调用 b() 时,我如何知道调用了哪个版本的 c()?

【问题讨论】:

  • "方法的常量是签名的一部分,对吗?"是的,左值/右值限定也是如此
  • 当我从 a 的非常量实例调用 b() 时,我如何知道调用了哪个版本的 c()? ... const 方法只能调用其他const方法,所以b() const只能调用c() const

标签: c++ c++11 constants


【解决方案1】:

从声明为 const 的函数内部,您只能调用该类型的 const 函数。

【讨论】:

  • 如果函数不是 const 怎么办?我怎么知道会叫哪一个?
  • 非常量一,如果有的话。否则,可以调用 const 。
  • 总是按那个顺序?是标准规定的吗?
  • @Nin 是的,标准中规定了。我建议你查一下。
【解决方案2】:

但是当它被另一个方法调用时会发生什么?

与从外部调用时相同。

请记住,成员函数可以被描述为好像它们有一个不可见的第一个参数T* this。对于const 成员函数,T const* this

现在,这段代码:

class a{
   void b() const{
      c();
      //do fantastic things
   }
   const_iterator c() const;
   iterator c();
};

可以认为是:

class a{
   void b(a const* this) const{ // pseudo code
      c(this); // pseudo code
      //do fantastic things
   }
   const_iterator c(a const* this) const; // pseudo code
   iterator c(a* this); // pseudo code
};

随后调用了cconst 版本,因为你“传递”了一个指向a const 的指针,而不是a

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 2013-10-08
    • 2011-01-14
    相关资源
    最近更新 更多