如果我想使用基类实现,为什么我必须在派生类中实现虚函数?
Why do I have to implement a virtual function in a derived class if I want to use the base class implementation
我有一个纯虚拟基类和一个派生类。我知道我被允许在基类中实现虚(非纯)方法。我不明白的是,如果我想要的只是简单地使用基本实现,为什么我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 {
这样,您就可以使用基类中的公共方法。
相关文章:
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 如何在从抽象基派生的类中实现相同的方法?
- 对派生自同一基类的类实现冲突检查
- 使用模板实现派生类
- 如何为具有私有成员的派生类实现移动构造函数
- 关于C++从派生类调用在基类中实现的虚拟函数的问题
- 如何在基类中定义静态接口,并确保该接口必须在派生类中实现
- 如何在派生类上强制实现特定数据类型的构造函数?
- C++派生类中的纯虚函数实现
- C :在f的派生类实现中,可以用x的子类型代替纯虚拟函数f的参数x
- 确保派生的类实现至少是来自抽象类(C )的两种方法之一
- C 结构实现派生接口
- 两个子级具有相同的 F() 实现,另外两个子级具有不同的 F 实现,所有四个子级都派生自同一类
- 如何在C++中正确表达具有相同实现的两个派生类函数?
- 如果不在派生类实现中执行此操作,"basic_streambuf"是否会创建自己的获取/放置区域?
- C++通过映射并使用中的方法从基类实现派生类
- 如何在指针的向量上实现派生类的复制构造函数到具有派生类实例的基类
- 为什么C++不允许基类实现派生类的继承接口?
- 实现派生类构造函数时出错:"重载函数的任何实例都与指定的类型匹配