首页 > 解决方案 > 基类中的受保护纯虚函数如何被基类的朋友类使用?

问题描述

我有一个抽象基类

class Base {
friend class Friend;
public:
    virtual ~Base() {}
protected:
    virtual void eval() = 0;

};

class Derived: public Base {
public:
     Derived = default;
protected:
     virtual void eval() { // implementation of eval()}
};

请注意,类 Friend 是 Base 的朋友,而不是 Derived。我的问题是:Friend 可以使用指向 Base 的指针调用 eval() 吗?例如,

void Friend::foo() {
    shared_ptr<Base> bpt(new Derived);
    bpt->eval()
}

标签: c++oop

解决方案


对类成员的访问是基于静态类型而不是动态类型确定的。静态类型的指针在 vtable 中可以访问Base*,但调用被路由到动态类型的成员函数。Friendeval()Base


推荐阅读