如何调用在C ++中具有抽象基类和派生类的定义的基类的虚函数定义? [英] How can I call virtual function definition of base class that have definitions in both abstract base class and derived class in C++?

查看:97
本文介绍了如何调用在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);
}

这篇关于如何调用在C ++中具有抽象基类和派生类的定义的基类的虚函数定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆