具有const修饰符的成员函数。

时间:2013-08-30 11:17:30

标签: c++ overloading

我有一个有两个成员函数的类,它们只有const修饰符不同。

class CFoo
{
private:
    int x;
    int y;
public:
  static int a;
  void dosmth() const {
      a = 99;
  }
  void dosmth(){
      x++;
      y++;
  }
};

int CFoo::a = 100;

int main(){
    CFoo foo;
    cout << CFoo::a << endl;
    foo.dosmth();
    cout << CFoo::a << endl;
}

以下代码打印100, 100。为什么要调用非const dosmth?如何明确调用const版本?

2 个答案:

答案 0 :(得分:4)

  

为什么要调用非const dosmth?

这是设计上的。如果你有一个非const对象,则选择非{const}重载超过const

  

我可以明确地调用const版本吗?

您需要一个对象为const的上下文。例如,

void dofoo(const Foo& f) { f.dosmth(); }
int main()
{
  CFoo foo;
  dofoo(foo);
  cout << CFoo::a << endl;

int main()
{
  const CFoo foo1{};
  foo1.dosmth();
  CFoo foo2;
  const_cast<const CFoo&>(foo2).dosmth();
}

答案 1 :(得分:3)

仅在对象本身为const时调用const版本。这意味着您可以使用以下代码调用const版本:

int main(){
    const CFoo foo;
    cout << CFoo::a << endl;
    foo.dosmth();
    cout << CFoo::a << endl;
}