运行超类重写的函数

run superclasses overridden function

本文关键字:函数 重写 超类 运行      更新时间:2023-10-16

如何从子类中重写的函数中调用超类中的重写函数?

例如:class super有一个叫做foo的函数,它在一个叫做sub的子类中被覆盖,如何让subs foo调用super foo?

您可以利用继承!

class A
{
public:
    virtual void Foo()
    {
        // do some base class foo-ing
    }
};
class B : public A
{
public:
    virtual void Foo()
    {
        // do some subclass foo-ing
        // to call the super-class foo:
        A::Foo( );
    }
};
void main()
{
    B obj;
    obj.Foo( );
    // This is if you want to call the base class Foo directly using the instance obj
    A* handle = &obj;
    handle->Foo( );
}

我想您谈论的是覆盖,而不是重载。对函数的合格调用不会使用动态调度机制,您可以控制选择什么覆盖:

struct base {
   virtual void foo() {...}
};
struct derived : base {
   virtual void foo() {
      base::foo();           // call the override at 'base' level
      ...
   }
};

如果你真的在谈论重载,你可以使用相同的机制,或者你可以将重载带入派生类型的范围:

struct base {
   void foo(int);
};
struct derived : base {
   using base::foo;           // make all overloads of base::foo available here
   void foo(double);
   void f() { base::foo(1); } // alternatively qualify the function call
};

您可以使用super::foo。例如:

#include <stdio.h>
class A
{
public:
    void foo(void)
    {
        printf("Class An");
    }
};
class B : public A
{
public:
    void foo(void)
    {
        printf("Class Bn");
        A::foo();
    }
};
int main ()
{
    B b;
    b.foo();
}