1

考虑这段代码

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::printI callBase::print这很好,直到我决定从我那里派生DerivedBaseA因此我当然想调用BaseA::print. 在这个特定示例中更改Base::printBaseA::print不是问题,但是如果我有 20 个这样的虚拟函数怎么办?

如何要求编译器调用直接父版本的print任何内容?

4

2 回答 2

2

使用 typedef:

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

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

于 2012-11-29T09:13:05.510 回答
0

您可以尝试使用模板:

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

然后你可以添加一个typedef:

typedef test<myBaseClass> myDerivedClass;
于 2012-11-29T09:21:00.717 回答