虚函数打破私有访问 [英] Virtual function breaking private access

查看:189
本文介绍了虚函数打破私有访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在 IBM站点。下面是示例代码

I recently came across this article on IBM site. Below is the sample code

#include "iostream"

class B {
public:
  virtual void f()
  {
    std::cout<<"\n In class B";
  }
};

class D : public B {
private:
    int i;

  void f()
  {
  std::cout<<"\n In class D i = "<<i;
  }
  public:
    D(int i_num):i(i_num)
    {}
};

int main() {
  D dobj(10);
  B* bptr = &dobj;
  D* dptr = &dobj;

  // valid, virtual B::f() is public,
  // D::f() is called
  bptr->f();

  // error, D::f() is private
  //dptr->f();
}

我们现在可以调用DI的私有函数想知道这个打破C ++封装?

We are now able to call private function of D.I wanted to know doesn't this break C++ encapsulation ?

:请转到虚拟功能中的虚拟功能访问部分。

P.S. : Please go to Virtual function access section in Virtual function. I do not know why I am not getting exact link when I do paste.

推荐答案

访问指定符是编译时构造,因此,编译器根据对象(或指针)的 static 类型检测编译时的任何违反访问规则(显然)。

Access-specifiers are compile-time construct, and so, the compiler detects any violation of access-rules at compile-time (obviously) based on the static type of the object (or pointer). Such violation cannot be detected at runtime.

所以 bptr-> f()可以工作,因为编译器看到 bptr static 类型是 B ,其中有因此表达式 bptr-> f() 通过编译器的测试。因此,它工作。

So bptr->f() works, because the compiler sees that the static type of bptr is B which has a public function f() defined, so the expression bptr->f() passes the compiler's test. Hence it works.

dptr-> f() D 的静态类型 dptr ,因此代码甚至不会编译!

But dptr->f() doesn't work, since the static type of dptr is D which has a private function f(), hence the code wouldn't even compile!

现在是否打破封装是一个非常主观的问题, 。它完全取决于如何定义它和参数直接流从它。没有一个通用的定义。我个人的意见是,如果语言允许,那么(这意味着)根据C ++社区,它不打破封装,或者如果它,然后C + +允许它,以实现一些非常诺贝尔是不可能的)。否则,我会说它只是另一个C ++错误,如下所示:

Now whether it breaks encapsulation or not, is a very subjective question and will receive subjective answers. It entirely depends on how one defines it and the arguments directly flows from it. There is no one universal definition. My personal opinion is, if the language allows it, then (it would imply that) according to the C++ community, it doesn't break encapsulation, or if it does, then C++ allows it so as to achieve something very nobel (which otherwise isn't possible). Otherwise, I would say its just yet another misfeature of C++ just like the following:

参数列表中间的默认参数?

这篇关于虚函数打破私有访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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