如果我想使用基类实现,为什么我必须在派生类中实现虚函数?

Why do I have to implement a virtual function in a derived class if I want to use the base class implementation

本文关键字:实现 派生 函数 为什么 基类 如果      更新时间:2023-10-16

我有一个纯虚拟基类和一个派生类。我知道我被允许在基类中实现虚(非纯)方法。我不明白的是,如果我想要的只是简单地使用基本实现,为什么我HAVE也要在派生类中实现相同的方法:

#include <iostream>
using namespace std;
class Abstract {
public:
    int x;
    Abstract(){
        cout << "Abstract constructor" << endl;
        x = 1;
    }
    virtual void foo() = 0;
    virtual void bar(){
        cout << "Abstract::bar" << endl;
    }
};
class Derived : Abstract {
public:
    int y;
    Derived(int _y):Abstract(){
        cout << "Derived constructor" << endl;
    }
    virtual void foo(){
        cout << "Derived::foo" << endl;
    }
    virtual void bar(){
        Abstract::bar();
    }
};
int main()
{
   cout << "Hello World" << endl;
   Derived derived(2);
   derived.foo();
   derived.bar(); //HERE I HAVE TO DEFINE Derived::bar to use it
   return 0;
}

你不必这么做。您可以执行以下操作:

class Derived : public Abstract {

这样,您就可以使用基类中的公共方法。