gpt4 book ai didi

c++ - 是否可以使用 static_cast 破坏 protected 成员访问检查?

转载 作者:搜寻专家 更新时间:2023-10-31 00:51:35 25 4
gpt4 key购买 nike

<分区>

考虑

class A {
protected:
int m;
};
class B : public A {
void foo(A& a) {
a.m = 42; // ill-formed
}
void bar(A& a) {
auto pm = &B::m;
auto pm2 = static_cast<int A::*>(pm);
a.*pm2 = 42; // is this ok?
}
};

根据 [class.protected],尝试直接访问 A::m 是格式错误的。然而,我们似乎总能(?)使用 static_cast 来规避这一点,它允许使用指向成员的指针进行派生到基的转换。或者这是某种 UB?

[ Coliru link显示 bar 编译]

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com