Call hidden (non virtual) method of derived class from base

旧城冷巷雨未停 提交于 2020-01-24 19:25:06

问题


Is there a way (templates, macros anything else) to substitute a call to hidden_in_derived from common method at compile time, so that instance of Derived calls it's own hidden_in_derived (without making hidden_in_derived virtual in Base) ?

#include <iostream>

class Base {
public:
    void common() {
        // some calls to other methods
        hidden_in_derived();
        // yet some calls to other methods
    }

    void hidden_in_derived() {
        std::cout << "A" << std::endl;
    }
};

class Derived : public Base {
public:
    void hidden_in_derived() {
        std::cout << "B" << std::endl;
    }
};


int main() {
    Derived d;
    d.common(); // want hidden_in_derived (prints "B") here somehow ?

}


回答1:


Make it virtual, then you can even use Base class ptr: https://wandbox.org/permlink/tF5Cb4fE5jEhG5Ru

Or just like you did with an object: https://wandbox.org/permlink/W2EJGXwioXjqd1Zx



来源:https://stackoverflow.com/questions/59087461/call-hidden-non-virtual-method-of-derived-class-from-base

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!