纯虚函数是抽象基类的必备属性。所以不应该做任何实现,这是非常直观的理解。但是最近我开始知道纯虚函数仍然可以在以后定义并静态调用(而不是通过对象实例)。我想不出一个理由。如果一个虚函数被定义为纯虚函数,那么实现它的原因是什么?
class A{
public:
...
virtual void interface() = 0; //Pure Virtual functions
...
}
void A::interface() //Implementation
{
cout<<"This the implementation for A interface";
}
我很好奇这背后的逻辑。为什么c++要这样设计?
最佳答案
拥有一个“默认”实现可能是有意义的,如果具体类对它们有用,则可以使用这些实现。他们仍然需要覆盖它,但可以非虚拟地调用基类版本:
struct B : A {
void interface() {
A::interface(); // call the default implementation
// and maybe do some B-specific things too
}
};
关于c++ - 实现纯虚函数的必要性是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20380585/