在下面的简化示例中,我尝试使用父类的现有实现来实现函数(从接口(interface))。
我想知道是否有人可以解释为什么这不起作用以及是否有一个简单的解决方法。

using namespace std;

struct IInterface
{
  virtual void vFunction () = 0;
};

struct Base
{
  void vFunction () { }
};

struct A: public Base, public IInterface
{
  using Base::vFunction;
  //virtual void vFunction() { Base::vFunction(); } // Is this the only way to reuse Base code?
};

int main ()
{
  A a;
  IInterface *pInterface = &a;

  a.vFunction();

  pInterface->vFunction();

  return 0;
}

错误是:
main.cpp: In function 'int main()':
main.cpp:21:9: error: cannot declare variable 'a' to be of abstract type 'A'
       A a;
         ^
main.cpp:13:12: note:   because the following virtual functions are pure within 'A':
     struct A: public Base, public IInterface
            ^
main.cpp:5:20: note:    virtual void IInterface::vFunction()
       virtual void vFunction () = 0;
                    ^

最佳答案

vFunction中的basevFunction中的IInterface没有关系。因此,编译器无法自动使用一种方法来代替另一种方法。您的转发代码是执行此操作的唯一方法。

关于c++ - 使用父类代码实现纯虚函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49698559/

10-11 19:11