c++ - static_cast 限制对公共(public)成员函数的访问?

标签 c++ templates inheritance access-modifiers static-cast

在以下示例的 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/

相关文章:

C++ 使用 <algorithm> 对 vector 的 vector 进行划分

c++ - 嵌套模板问题

C++ 模板结构 'has no member named' 错误

inheritance - Java:方法是否继承 JRE 父类(super class),就像类继承 Object 一样?

c++ - 如何使用 C++ 将 Boost ptree 插入 MongoDB

c++ - 我应该担心用户可能会弄​​乱我的程序文件吗?

c++ - 如何使用 C++ 模板实现从类型到对象方法调用的映射?

c++ - MFC::使用结构传递数据

c# - 条件运算符会感到困惑,但为什么呢?

c++ - OpenGL glm::translate 没有像希望的那样翻译矩阵