所以一个任务:我们有一个第三方库,有一个类(叫它Base)。该库提供了一个隐藏的实现,称为 Impl。我需要写一个代理。不幸的是 Base 有一个受保护的虚函数 fn。
所以问题是从 C++ 的角度来看,下面的代码在多大程度上是正确的?它目前在 Visual Studio 中完美运行,并且在 Mac 上的 clang/gcc 中无法运行(但编译时没有任何警告)。我很清楚那里发生的机制,所以如果删除类问题,一切都可以在两个平台上运行。我想知道我是否应该向 clang 报告错误,或者它是 C++ 标准的未定义/未指定行为。
代码的预期结果是正常调用 Impl::fn()
class Base
{
protected:
virtual void fn(){}
};
class Impl : public Base
{
public:
Impl() : mZ(54){}
protected:
virtual void fn()
{
int a = 10; ++a;
}
int mZ;
};
class Problem
{
public:
virtual ~Problem(){}
int mA;
};
class Proxy : public Problem, public Base
{
public:
virtual void fn()
{
Base * impl = new Impl;
typedef void (Base::*fn_t)();
fn_t f = static_cast<fn_t>(&Proxy::fn);
(impl->*f)();
delete impl;
}
};
int main()
{
Proxy p;
p.fn();
}