[英]C++ How to access derived class member from base class pointer without using a static_cast or dynamic_cast?
[英]In C++ how could I cast a sub class instance from one base class pointer to another without dynamic_cast?
我想在没有dynamic_cast
情况下这样做:
class A {};
class B {};
class C : public A, public B {};
void func()
{
A* pClassA = new C();
B* pClassB = what_cast<B*>(pClassA); // what could the cast be?
}
我认为类型ClassC
的实例可以表示为ClassA
和ClassB
。 现在,如果我只能获得ClassA
类型的指针,如何在没有dynamic_cast
情况下将其转换为ClassB
?
A
和B
是不相关的类型,所以你不能只在它们之间施放。 只要您确定 pClassA
指向C
,您就可以对C*
进行中间pClassA
转换,然后依靠隐式的派生到基础转换来获取B*
:
B* pClassB = static_cast<C*>(pClassA);
或者您可以通过C*
明确地转换为B*
:
B* pClassB = static_cast<B*>(static_cast<C*>(pClassA));
在设计良好的代码中,几乎不会发生这种类型的问题。 所以,更好地重新思考你的设计。 也许你想要避免多态,当你真的应该使用它? 你可以
struct B; // forward decl
struct A {
virtual B*this_as_B_ptr() { return nullptr; }
const B*this_as_B_ptr() const { return const_cast<A*>(this)->this_as_B_ptr(); }
virtual~A() {}
};
struct B { /* ... */ }; // may be in different header
struct C:A,B // may be in yet different header
{
B*this_as_B_ptr() override { return this; }
};
A* pA = new C;
B* pB = pA->this_as_B_ptr();
- 有效实施更有效的动态投射方式。
您可以使用一些强制转换将pClassA
转换为B*
,包括reinterpret_cast
和C风格的强制转换。
你真正的问题是“如何在没有dynamic_cast
情况下安全地投射它。好吧,虽然你可以做各种对象验证机制,但我怀疑你真的需要它们。
dynamic_cast
什么问题?
编辑:嗯。 我更喜欢Idiomatic C ++而不是技巧,但有时你确实需要原始大小/速度。 我会选择一些标记机制:
enum Types{AType,BType,CType};
struct A {
int type;
A(): type(AType) {}
bool is (Types wantedType) {return (type & wantedType) == wantedType; }
};
struct B {
};
struct C : public A, public B {
C(){ type = (type | CType) | BType ; }
};
这样你静态地询问对象是否来自类型Types
实际运行: http : //coliru.stacked-crooked.com/a/1774f9c85603fa31
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.