1

有没有办法(模板,宏任何其他)在编译时替换从通用方法调用hidden_​​in_derived,以便 Derived 的实例调用它自己的hidden_​​in_derived而不在 Base中使hidden_​​in_derived虚拟)?

#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 ?

}

4

1 回答 1

0

使其虚拟化,然后您甚至可以使用基类 ptr:https ://wandbox.org/permlink/tF5Cb4fE5jEhG5Ru

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

于 2019-11-28T11:15:55.510 回答