从基类中调用派生类的隐藏(非虚拟)方法 [英] Call hidden (non virtual) method of derived class from base

查看:92
本文介绍了从基类中调用派生类的隐藏(非虚拟)方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法(模板,宏,其他任何方法)可以替代在 编译时从 common 方法对 hidden_​​in_derived 的调用,因此Derived实例会调用它自己的 hidden_​​in_derived ( 使Base中的 hidden_​​in_derived 虚拟) ?

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 ?

}

推荐答案

将其设为虚拟,您甚至可以使用基类ptr:

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

或者就像您对一个对象所做的那样: https://wandbox.org/permlink/W2EJGXwioXjqd1Zx

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

这篇关于从基类中调用派生类的隐藏(非虚拟)方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆