私有函数成员在类之外调用

tes*_*ram 15 c++ c++11

在下面的例子中,为什么B::f()即使它是私有的呢?

我知道这一事实:使用表达式的类型在调用点检查访问,该表达式用于表示调用成员函数的对象.

#include <iostream>

class A {
public:
  virtual void f() { std::cout << "virtual_function"; }
};

class B : public A {
private:
  void f() { std::cout << "private_function"; }
};

void C(A &g) { g.f(); }

int main() {
  B b;
  C(b);
}
Run Code Online (Sandbox Code Playgroud)

Lig*_*ica 23

因为标准如此说:

[C++11: 11.5/1]:虚函数的访问规则(第11条)由其声明确定,并且不受稍后覆盖它的函数规则的影响.[例如:

class B {
public:
  virtual int f();
};
class D : public B {
private:
  int f();
};
void f() {
  D d;
  B* pb = &d;
  D* pd = &d;
  pb->f();       // OK: B::f() is public,
                 // D::f() is invoked
  pd->f();       // error: D::f() is private
}
Run Code Online (Sandbox Code Playgroud)

- 末端的例子]

这个例子和你的一样,哈哈.


Col*_*mbo 6

private函数可以覆盖public基类中的虚函数.事实上,在确定某个函数是否会覆盖另一个函数时,完全忽略了可访问性,即使在函数中也是如此

// Redundant private for clarity:
class A { private: virtual void foo(); };
class B : A { public: void foo(); };
Run Code Online (Sandbox Code Playgroud)

B::foo覆盖A::foo.

  • 这个例子不是很有趣,因为`B`声明`foo`私有就像'A`那样,_and_它私下继承. (2认同)