c++ - 基类中的受保护纯虚函数如何被基类的朋友类使用?
问题描述
我有一个抽象基类
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()
}
解决方案
对类成员的访问是基于静态类型而不是动态类型确定的。静态类型的指针在 vtable 中可以访问Base*
,但调用被路由到动态类型的成员函数。Friend
eval()
Base
推荐阅读
- opencv - 提取矩形,放下它并在opencv中旋转图像
- javascript - 更改为 React State 不会更新功能组件中的显示
- python - 具有不同 line_dash 的 Python Bokeh 多线图
- webpack - 使用 vue-cli 设置时如何从 babel-loader 中排除特定文件?
- javascript - Javascript For Loop 在 Chrome 插件中重复执行,但仅从控制台执行一次
- ios - (iOS + Firebase)无法将图像从 UITableViewCell 传递给下一个 ViewController
- android - ConstraintSet 克隆崩溃
- angular - 如何使 npm install 依赖于自定义位置并避免包装在 node_modules 中?
- gradle - Xamarin gradle 绑定 android
- entity-framework - 添加实体而不获取