我如何调用基类的虚拟函数定义,这些定义在Ampract Base类和C 中的派生类中都有定义

How can I call virtual function definition of base class that have definitions in both abstract base class and derived class in C++?

本文关键字:定义 Base Ampract 类和 派生 何调用 调用 函数 虚拟 基类      更新时间:2023-10-16

我们无法创建一个抽象类的对象,对吗?那么,如何调用在抽象基类和派生类中都具有定义的虚拟函数呢?我想在抽象基类中执行代码,但目前,我正在使用派生类的对象。

class T
{
   public:
   virtual int f1()=0;
   virtual int f2() { a = 5; return a }
}
class DT : public T
{
   public:
   int f1() { return 10; }
   int f2() { return 4; }
}
int main()
{
    T *t;
    t = new DT();
    ............
}

有什么办法可以使用对象t调用基类函数?如果不可能,我应该怎么做才能调用基类功能?

就像您将调用任何其他基类实现一样:使用明确的资格绕过动态调度机制。

struct AbstractBase
{
  virtual void abstract() = 0;
  virtual bool concrete() { return false; }
};
struct Derived : AbstractBase
{
  void abstract() override {}
  bool concrete() override { return true; }
};
int main()
{
  // Use through object:
  Derived d;
  bool b = d.AbstractBase::concrete();
  assert(!b);
  // Use through pointer:
  AbstractBase *a = new Derived();
  b = a->AbstractBase::concrete();
  assert(!b);
}

您可以在调用函数时明确指定类范围:

  class A { /* Abstract class */ };
  class B : public A {}
  B b;
  b.A::foo();

如果抽象基类有一些代码,则只需致电baseclassname :: AbstractFunction()

class Base
{
    virtual void Function()  {}
}
class Derived : Base
{   
    virtual void Function() { Base::Function(); }
}