如何调用在C ++中具有抽象基类和派生类的定义的基类的虚函数定义?

如何调用在C ++中具有抽象基类和派生类的定义的基类的虚函数定义?

问题描述:

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

We can't create an object of an abstract class, right? So how can I call a virtual function which has definition in both abstract base class and derived class? I want to execute the code in abstract base class but currently, I am using derived class's object.

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调用基类函数吗?如果不可能,我该怎么做才能调用基类函数?

Is there any way I can call the base class function using the object t? If it is not possible, what should I need to do to call the base class function?

就像您将调用任何其他基类实现一样:使用显式限定条件绕过动态调度机制.

Just like you would call any other base class implementation: use explicit qualification to bypass the dynamic dispatch mechanism.

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);
}