在以下示例的 static_cast 中出现“错误:‘A’是‘B’的不可访问基数”:
template<typename Derived>
class A {
protected:
void funA() { static_cast<Derived *> (this)->funB(); }
};
class B: protected A<B> {
public:
void funB() {}
void funC() { funA(); }
};
int main() {
B().funC();
return 0;
}
但它在使用 reinterpret_cast 或 C 风格类型转换 ((Derived *)this)->funB() 时编译/工作良好。这种行为是否正确?
使用的编译器: gcc 版本 4.5.1 20100924 (Red Hat 4.5.1-4) (GCC)。
谢谢。
最佳答案
I'm getting "error: ‘A’ is an inaccessible base of ‘B’" in
static_cast
of the following example:
这是预期的:B
源自 A<B>
, 但此继承 protected :仅 B
及其派生类可以使用事实 B
源自 A<B>
.
But it compiles/works well when using
reinterpret_cast
(...) instead. Is this behavior correct?
这是预期的:reinterpret_cast
不关心类型之间的继承或其他关系。
如果可能,reinterpret_cast
只是给你一个与原始指针值具有相同值(指向相同字节)的指针。
这只是隐藏了问题。
But it compiles/works well when using (...) C-style type cast
((Derived *)this)->funB()
instead. Is this behavior correct?
这是意料之中的:C 风格的转换忽略访问控制。 这只是隐藏了问题。
解决方法是在A<B>
之间建立继承关系。和 B
在您想使用它的地方访问。
关于c++ - static_cast 限制对公共(public)成员函数的访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8548667/