考虑这段代码
class Base
{
public:
virtual void print ()
{
std::cout << "Base::print" << std::endl;
}
};
class BaseA : public Base
{
public:
virtual void print ()
{
std::cout << "BaseA::print" << std::endl;
}
};
class Derived : public Base
{
public:
virtual void print ()
{
Base::print (); // <= this will always call Base::print even if I derive from BaseA
std::cout << "Derived::print" << std::endl;
}
};
int main ()
{
Base* a = new Derived;
a->print ();
delete a;
}
From Derived::print
I callBase::print
这很好,直到我决定从我那里派生Derived
,BaseA
因此我当然想调用BaseA::print
. 在这个特定示例中更改Base::print
为BaseA::print
不是问题,但是如果我有 20 个这样的虚拟函数怎么办?
如何要求编译器调用直接父版本的print
任何内容?