考虑这段代码
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;
}
从 Derived::print
我调用 Base::print
这很好,直到我决定从 BaseA 派生我的
而不是,因此我当然想调用 Derived
BaseA::print
。在这个特定示例中将 Base::print
更改为 BaseA::print
不是问题,但是如果我有 20 个这样的虚函数怎么办?
无论那是什么,如何要求编译器调用 print
的直接父版本?
最佳答案
使用类型定义:
class Derived: public BaseA {
typedef BaseA Base;
...
尽管有提议(例如 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3326.pdf),但目前无法对类的直接基类进行编译时自省(introspection)。
关于c++ - 如何可靠地调用直接父级的虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13622145/