为什么 c++ 允许直接从 child class 中调用祖父母 class 方法?

Why c++ allows to call grandparent class method directly from within child class?

为什么 C++ 允许直接从 child class 中调用 grandparent class 方法。这不违反封装吗? Java 之类的语言不允许绕过 parent class 方法意味着 super.super.method() 是不允许的。但它在 C++ 中有效。是什么原因?考虑以下代码。

#include <iostream>
class a1 
{
  public:
  void fun()
 {
    std::cout<<"fun() in a1\n";
 }
};

class a2 : public a1
{
   public:
   void fun() 
   {
       std::cout<<"fun() in a2\n";
   }
};

class a3 : public a2
{
   public:
   void fun()        // Bypass call to a2 class' method
   {
       a1::fun();
       std::cout<<"fun() in a3\n";
   }
};

int main()
{
     a3 a;
     a.fun();
     return 0;
}

Python 有一个基本范例:"we are all educated grown-ups"。换句话说:语言的设计者明白某些特性可能会被滥用;但他们指望程序员要小心。

在我看来,它与C++非常相似;它只是不像 python 那样是 "official mantra"。

您问的是:

Doesn't that violate encapsulation?

在一定程度上确实如此。理想情况下,如果 a3 需要从其祖先 类 访问任何功能,它应该通过其直接基础 类,即父 类。如果设计发生变化并且 a2 不再派生自 a1,则 a3::fun 中的代码将会中断。

您问的是:

What is the reason?

很可能有一长串原因,太长而无法放入 SO 答案中。我怀疑主要原因是允许程序员灵活地做对他们有意义的事情。