在类外调用的私有函数成员 [英] Private function member called outside of class

查看:544
本文介绍了在类外调用的私有函数成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In the example below, why is B::f() called even though it is private?

我知道这个事实:
在调用点处使用表示成员函数被调用的对象的表达式类型来检查访问。

I know this fact that : Access is checked at the call point using the type of the expression used to denote the object for which the member function is called.

#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);
}


推荐答案


[C ++ 11:11.5 / 1]:访问规则用于虚拟函数的子句11)由其声明确定,并且不受随后覆盖它的函数的规则的影响。 [示例:

[C++11: 11.5/1]: The access rules (Clause 11) for a virtual function are determined by its declaration and are not affected by the rules for a function that later overrides it. [ Example:

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
}

end example]

—end example ]

示例与您的lol相同。

The example is the same as yours, lol.

这篇关于在类外调用的私有函数成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆