如果我想使用基础 class 实现,为什么我必须在派生 class 中实现虚函数
Why do I have to implement a virtual function in a derived class if I want to use the base class implementation
我有一个纯虚拟基础 class 和一个派生 class。我知道我可以在基础 class 中实现一个虚拟(非纯)方法。
我不明白的是为什么我 HAVE
也在派生 class 中实现相同的方法,如果我想要的只是使用基本实现:
#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 {
这样,您就可以使用基础 class 中的 public 方法。
我有一个纯虚拟基础 class 和一个派生 class。我知道我可以在基础 class 中实现一个虚拟(非纯)方法。
我不明白的是为什么我 HAVE
也在派生 class 中实现相同的方法,如果我想要的只是使用基本实现:
#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 {
这样,您就可以使用基础 class 中的 public 方法。