c++ - 为什么reinterpret_cast在私有(private)继承中起作用

标签 c++ casting reinterpret-cast

我在应用继承时阅读了有关访问说明符的内容,并且我知道在私有(private)继承中,我们无法使用指针/引用从派生类转换为基类。

但是当我使用reinterpret_cast时它起作用了。下面是我的测试代码:

class base {
int _a;
public: 
    base(int a): _a(a) {}
    base(): _a(0) {}
};

class derived : private base
{
public:
    derived(int b):base(b) {};  
};

int main() {

    derived b(25); 
    base &a = static_cast<base&>(b);//this line will generate a compile error
    base &c = reinterpret_cast<base&>(b);  //here it works 
}

所以我的问题是即使进行私有(private)继承,为什么基类会使用 retinterpret_cast 公开?

谢谢!

//编辑2

class base {
    int _a; 
public:         
    base(int a): _a(a) {}
    base(): _a(100) {}  
    ~base() { std::cout << "deleting base" << _a << "\n"; }
};

class derived : private base
{
public:
    virtual ~derived() = default;
    derived(int b):base(b) {};
};

int main() {

    derived b(25); 
    base &c = reinterpret_cast<base&>(b); 
}

//OutPut : Deleting 25

最佳答案

是否侵犯了私有(private)继承?事实并非如此。

C++ 中的可访问性仅影响标识符可用于以有效方式引用某些内容的范围。该系统旨在防范墨菲,而不是像您使用的马基雅维利伎俩。

reinterpret_cast 基本上就是告诉编译器“忘记你所知道的,相信我的判断”。确实如此。您声称这个左值实际上引用了base?好吧,随你的便吧。但是编译器不会做任何事情来保护你,它假设你知道你在做什么。它很容易破裂。有 @Dani 的例子,还有这个:

class derived : private base
{
public:
    virtual ~derived() = default;
    derived(int b):base(b) {};  
};

如果您尝试使用 c 并调用使用 _a 的成员函数,您认为会发生什么?它会发现什么?

关于c++ - 为什么reinterpret_cast在私有(private)继承中起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51151986/

相关文章:

java - Swift 中的 Java Object 等价物是什么?

c++ - 使用 constexpr 绕过重新解释强制转换限制

c++ - Placement new,对象放置在 I/O 寄存器和归零内存上

c++ - 正则表达式:查找标签列表作为行尾

c++ - 在 Visual Studio 中直接调用 MATLAB(多线程)

c++ - 在 C++ 中添加类?

c++ - 如何使arduino无人机具有侧倾,俯仰和偏航值稳定?

java - 将 PgArray 或 java.sql.Array 转换为 Scala 集合

objective-c - NSNotification 上的对象是否需要强制转换?

c++ - 使用 static_cast(或 reinterpret_cast)进行不添加成员的继承的无效向下转换的安全性