虚函数的继承

Inheritance of a Virtual Function

本文关键字:继承 函数      更新时间:2023-10-16

我有以下一段代码。

class A {
public: 
  virtual void foo() = 0;
}
class B : public A {
public:
  void bar() { /* Do something */ }
}
void B::A::foo() {
   bar();
   // Do something else
}

当我尝试编译这个时...我收到一个错误,说它找不到bar()。这不是实例化纯虚函数的正确方法吗?

use of undeclared identifier 'bar'
void B::A::foo()没有

多大意义。看起来你的意思是在B中实现foo(),为此你需要在B的类声明中声明它,然后实现它:

class B : public A {
public:
  void foo();
  void bar() { /* Do something */ }
};
void B::foo() {
   bar();
   // Do something else
}

由于以下几个原因,您的代码将无法编译:

class A 
{
public: 
  virtual void foo() = 0; // this defining a pure virtual function - making A an abstract class
}; // missing ; here
class B : public A 
{
public:
  void bar() { /* Do something */ }
  // you never implement foo, making B another abstract class
}; // again with the ;
void B::A::foo() // this line makes no sense
{
   bar();
   // Do something else
}

我相信您要做的是以下内容

class A 
{
public: 
    virtual void foo() = 0;
};
class B : public A 
{
public:
    virtual void foo() { bar(); } // override A::foo
    void bar() { /* Do something */ }
};

如果要重写函数,则必须将其声明为已重写。 如果从抽象基类派生类并且未实现其函数,则派生类也是抽象基类。 在实例化任何类之前,其所有函数都必须是非抽象的。