为什么C风格转换允许你转换为私有基类? [英] Why does C style cast allow you to convert to a private base class?
问题描述
说我们有这个代码
class A {
public:
A() : x(1) {}
virtual ~A() {}
int x;
};
class B {
public:
B() : y(2) {}
virtual ~B() {}
void g()
{
cout << "B::" << y << endl;
}
int y;
};
class C : private A, private B {
public:
void f()
{
B* p = static_cast<B*>( this );
p->g();
}
};
int main()
{
C c;
((B*)&c)->g();
return 0;
}
主函数中的C风格转型无法正确表达C ++ casts( static_cast
, dynamic_cast
, reinterpret_cast
)。但是,首先允许这样做的原因是什么?它不会伤害封装吗?
The C style cast in the main function cannot be correctly expressed in terms of the C++ casts (static_cast
, dynamic_cast
, reinterpret_cast
). But what is the reason to allow this in the first place? Doesn't it hurt encapsulation?
UPDATE
这不是重复的链接问题,因为这个问题是关于设计C ++中的决策。它不问我能用或不能用语言做什么,它问为什么可能做出某些决定。
UPDATE This is not a duplicate of the linked question, because this question is about design decisions in C++. It does not ask what I can or cannot do with the language, it asks why certain decisions might have been made.
推荐答案
因为在C中允许使用这个转换将任何指针转换为任何其他指针,并且C ++尽可能地是C兼容的,但尝试做一个好的工作是正确的,当涉及到类,所以C风格的转型在这种情况下比 reinterpret_cast
更强。
It's because in C it was allowed to convert any pointer to any other pointer using this cast and C++ tries to be C-compatible as much as possible, but tries to do a good job to be correct when it comes to classes, so C style cast is stronger than reinterpret_cast
in this situation.
这篇关于为什么C风格转换允许你转换为私有基类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!