关于此错误有很多问题,所有答案似乎都暗示着向下转换是不可能的。至少据我所知,只有这个答案提到友谊是可能的解决方案。但是,以下代码(为清晰起见,删除了不相关的内容)无法编译:
class C;
class A {
friend class C; // this does not help
};
class B : protected A {
friend class C; // this does not help either
};
class C {
public:
void foo(A* a) {};
};
B b;
C c;
void bar()
{
c.foo(&b); // this produces error: class A is an inaccessible base of B
}
Run Code Online (Sandbox Code Playgroud)
为什么友情对参考无效?毕竟,“ C”完全有能力通过指向“ B”的指针来调用“ A”的受保护方法。
完整的错误是
prog.cc: In function 'void bar()':
prog.cc:20:13: error: 'A' is an inaccessible base …Run Code Online (Sandbox Code Playgroud)