C++方法只有返回类型(和const)的'constness'不同

anh*_*ppe 0 c++ overloading const

我偶然发现了一些我以前从未见过的东西.考虑一下你有以下课程:

class foo
{
    const bar* get() const;
    bar* get();
}
Run Code Online (Sandbox Code Playgroud)

foo的客户端如何决定使用哪种get()方法?

Rei*_*ica 8

就像constness上的任何其他重载一样,它取决于调用函数的对象的访问路径(换句话说,取决于隐式this参数的类型).

例:

void bar(foo nc1, foo &nc2, foo *nc3, const foo &c1, const foo *c2) {
  // These call the non-const version:
  nc1.get();
  nc2.get();
  nc3->get();

  // These call the const version:
  c1.get();
  c2->get();
}
Run Code Online (Sandbox Code Playgroud)