简体   繁体   English

为什么reinterpret_cast在私人继承中确实起作用

[英]Why reinterpret_cast does work in private inhertiance

I was reading about access specifiers when applying inheritance, and I know that in private inheritance we could not cast from a derived to a base class using pointers/references. 我在阅读有关应用继承时的访问说明符,并且我知道在private inheritance我们无法使用指针/引用将其从派生转换为基类。

But when I used reinterpret_cast it worked. 但是当我使用reinterpret_cast它起作用了。 below is my test code: 下面是我的测试代码:

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 
}

So my question is even doing private inheritance, why the base class would be exposed using retinterpret_cast ? 所以我的问题甚至是在进行私有继承,为什么使用retinterpret_cast公开基类?

Thank you! 谢谢!

//EDIT 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

Is private inheritance violated? 是否侵犯了私人继承? Not really. 并不是的。

Accessibility in C++ only affects in what scopes can an identifier be used to refer to something in a valid fashion. C ++中的可访问性仅影响标识符可以在什么范围内以有效方式引用事物。 The system is designed to protect against Murphy, not a Machiavellian trick like you use. 该系统旨在保护您免受Murphy的侵害,而不是像您使用的Machiavellian一样。

reinterpret_cast is basically you telling the compiler "forget what you know, trust my judgment instead" . reinterpret_cast基本上是您告诉编译器“忘记您所知道的,改为相信我的判断” So it does. 确实如此。 You claim this lvalue does in fact refer to a base ? 您声称这个左值实际上是指base Fine, have it your way. 很好,随你便便。 But the compiler isn't gonna do anything to protect you, it assumes you know what you are doing. 但是编译器不会做任何保护您的事情,它假设您知道自己在做什么。 It can break quite easily. 它很容易折断。 There's @Dani's example, and there's this one: 有@Dani的例子,有一个例子:

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

What do you think will happen if you try to use c and call a member function that uses _a ? 如果您尝试使用c并调用使用_a的成员函数,您会怎么办? What will it find instead? 它会找到什么呢?

reinterpret_cast is not the same as static_cast reinterpret_caststatic_cast
Consider the following example: 考虑以下示例:

class A { int a; }
class B { int b; }
class C : public A, B { }

Casting C to B using static_cast would change the pointer to the correct result, while reinterpret_cast would keep the pointer the same which is not correct. 使用static_cast将C转换为B会将指针更改为正确的结果,而reinterpret_cast会将指针保持不变,这是不正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM