c++ - 为什么调用直接父类的函数而不是祖父类的函数。这称为函数覆盖吗?

标签 c++

class A
{
public:
void test ()
{
cout<<"In A";
}
};
class B :public A
{
public:
void test ()
{
cout<<"In B";
}
};
class C : public B
{

public:
int c;
};
int main()
{
C c;
c.test();
}

The result is: In B...

最佳答案

不,它不是覆盖,而是隐藏原始方法。

C++ 中的多态行为仅限于声明为 virtual 的方法,类层次结构中该方法的每个实现都称为该方法的覆盖

struct base {
   virtual void foo();
   void bar();
};
struct derived : base {
   virtual void foo();
   void bar();
};

在示例中,base::fooderived::foo 被覆盖。当您通过类型为 base 的指针或引用使用类型为 derived 的类时,最终的覆盖方法将被调用(层次结构中的最低层:在本例中 派生::foo)。这里的重点是调用是通过指针或对基的引用:

void test() {
   derived d;
   base &b = d;
   b.foo(); // derived::foo() <- final overrider
   b.bar(); // base::bar()    <- non-virtual, no override
   d.bar(); // derived::bar() <- hides the method in base
}

bar 的情况下(或在您的情况下)发生的情况是,当编译器找到调用 d.bar() 时,它需要确定要调用的方法称呼。要找到该方法,它将首先查看 derived 声明,它会找到 derived::bar()(与 base::bar()) 并且它将使用该方法而不检查类层次结构中的更高层。如果您需要调用层次结构中更高层的方法,您可以通过获取对更高类型的引用或完全限定要调用的方法来实现。

请注意,隐藏不仅在签名完全匹配时发生,而且在编译器找到具有相同名称的方法的所有情况下发生:

struct base {
   void bar();
};
struct derived : base {
   void bar( int );
};
void test() {
   derived d;
   base & b;

   b.bar();    // ok: base::bar()
   d.bar(1);   // ok: derived::bar(int)
   //b.bar(1); // error: base has no bar method that takes an integer
   //d.bar();  // error: derived::bar takes an integer, base::bar is hidden
   d.base::bar(); // ok: fully qualifying tells the compiler where to look
}

关于c++ - 为什么调用直接父类的函数而不是祖父类的函数。这称为函数覆盖吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2483227/

相关文章:

c++ - 如何在嵌入式平台中管理不同 Pin-Out 板的代码以实现更好的 HAL 管理?

c++ - 交叉数据结构

c++ - 双向插入排序错误

C++ UDP客户端问题

c++ - "Forward-unbreakable"访问器类模板 [C++]

android - 如何在 Qt/Android 的默认外部编辑器中打开文件

c++ - Visual C++ 10(又名 2010)与 Visual C++ 9(又名 2008)相比

java - C++ 软件上的 API

c++ - SDL 图像在 15 秒后消失

c++ - 每个 QFont 的新 QFontDialog?