#include <iostream>
class Base
{
public:
virtual ~Base() {}
virtual void f()
{
std::cout << "base\n";
}
};
class Derived : public Base
{
public:
virtual ~Derived() {}
virtual void f()
{
std::cout << "derived\n";
}
};
int main()
{
Derived* D = new Derived;
D->f();
delete D;
return 0;
}
所以我打电话给Derived::f
,但我也打电话给Base::f
。还有其他方法,而不是在Base::f()
内调用Derived::f()
吗?
答案 0 :(得分:2)
听起来你想要的是Non Virtual Interface(NVI)设计。当你想要派生类的自定义点(例如多态),但是有点保证调用流时,这很好。
class Base
{
public:
virtual ~Base() {}
void f()
{
// ... do something that always run before
f_impl();
// ... and after the extension point
}
protected:
virtual void f_impl()
{
}
};
class Derived : public Base
{
protected:
virtual void f_impl() override
{
std::cout << "extended!\n";
}
};
int main()
{
Derived d;
d.f(); // Base can _always_ run things before and after Derived
}