【问题标题】:How to reliably call immediate parent's virtual function如何可靠地调用直接父级的虚函数
【发布时间】:2012-11-29 09:04:13
【问题描述】:

考虑这段代码

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 的直接父版本?

【问题讨论】:

  • 我注意到有关虚拟方法的问题的频率有所增加。
  • @Mark Garcia:一定是一个邪恶的阴谋。我们不应该提供答案——“他们”只会变得更强大。 (说真的,如果这是重复的,它可能是重复的,标记它,并引用原件。):)
  • @DavidO 这一切背后一定有人。
  • 我觉得你有问题。你相信你会总是想要调用直接基类的虚函数,即使你现在不知道基类是什么。我的水晶球说你实际上只想对 20 个虚拟中的 18 个这样做,而这个解决方案只是给你带来了一个新问题。更改继承结构时,您只需必须重新评估所有内容。

标签: c++ polymorphism overriding virtual


【解决方案1】:

使用类型定义:

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

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

【讨论】:

    【解决方案2】:

    您可以尝试使用模板:

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

    然后你可以添加一个 typedef:

    typedef test<myBaseClass> myDerivedClass;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      • 2010-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      相关资源
      最近更新 更多