如何可靠地调用直接父亲的虚函数

时间:2012-11-29 09:04:13

标签: c++ polymorphism override virtual

考虑这段代码

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这很好,直到我希望从Derived推导出我的BaseA,我当然希望拨打BaseA::print 。在此特定示例中将Base::print更改为BaseA::print不是问题,但如果我有20个这样的虚函数怎么办?

如何让编译器调用print的直接父版本,无论是什么?

2 个答案:

答案 0 :(得分:2)

使用typedef:

class Derived: public BaseA {
    typedef BaseA Base;
    ...

虽然有提案(例如http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3326.pdf),但目前无法对类的直接基础进行编译时内省。

答案 1 :(得分:0)

您可以尝试使用模板:

template <class base>
class test: public base
{
    virtual void testmethod()
    {
        base::testmethod();
    }
};

然后你可以添加一个typedef:

typedef test<myBaseClass> myDerivedClass;