【问题标题】:Is there any way I can call child method from parent class?有什么办法可以从父类调用子方法吗?
【发布时间】:2015-03-13 13:36:29
【问题描述】:

我正在为 cocos2d-x 构建一个游戏,并想从父类调用子类方法。

class Parent {
    *//do something
    //How can i call method from subchild class here?*
}

class Child : Parent {
    *//do something*
}

class SubChild : Child {
    void functionToBeCalledFromParent();
}

【问题讨论】:

  • 有一个简单的方法:在Parent 中使用虚函数,在SubChild 中覆盖。
  • 还有一个不太简单的方法:使用CRTP

标签: oop c++11 cocos2d-x


【解决方案1】:

我正在为 cocos2d-x 构建一个游戏,并想从父类调用子类方法

您可以 1) 在 parent 中声明函数并在 child 中定义它或 2) 在 parent 中定义它并在 child 中覆盖它(重新定义它)。

【讨论】:

    【解决方案2】:

    通过使用CRTP,您的示例

    class Parent {
        void callSubclassFunction() {
            //How can i call method from subchild class here?
        }
    }
    
    class Child : Parent {
    }
    
    class SubChild : Child {
        void functionToBeCalledFromParent();
    }
    

    会变成

    #include <iostream>
    
    template <typename TSubclass>
    class Parent {
    public:
        void callSubclassFunction() {
            static_cast<TSubclass*>(this)->functionToBeCalledFromParent();
        }
    };
    
    template <typename TSubclass>
    class Child : public Parent<TSubclass> {
    };
    
    class SubChild : public Child<SubChild> {
    public:
        void functionToBeCalledFromParent() {
            std::cout << "SubChild!" << std::endl;
        }
    };
    
    int main()
    {
        SubChild child;
        child.callSubclassFunction();
    }
    

    Runnable at Coliru

    SubChild 作为模板参数传递给Child&lt;&gt; 是可行的,因为类型名一经声明就有效,它位于继承列表分隔符: 的前面。

    Parent 中使用static_cast 来“向下转换”是完全良性的。如果子类没有定义Parent中调用的函数,编译就会失败。

    这种技术称为静态编译时多态性,它是ATL和WTL的基础。相反,也许更传统的方法是 dynamicruntime 多态性,这就是您使用虚函数所获得的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-09
      • 2012-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多