指向基类的指针
如果我有以下类:
class A
{
...
}
class B
{
...
}
class C : public A, public B
{
...
}
并且在某处我检测到我拥有的类 B
的指针实际上指向类 C
,但函数需要一个指向类 B
的指针code>A,我该怎么做才能获得指向类 A
的指针?
If I have the following classes:
class A
{
...
}
class B
{
...
}
class C : public A, public B
{
...
}
and somewhere I detect that the pointer of class B
that I have actually points to a class C
, but a function requires a pointer to class A
, what can I do to get that pointer to class A
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您确定有一个指向
C
对象的B*
对象,则可以使用一对static_cast
:跨继承层次结构进行强制转换的方法是使用
dynamic_cast
,它要求类型是多态的(也就是说,您的类必须至少有一个虚拟成员函数;因为您的基类析构函数应该是虚拟
,这通常不是问题):Dynamic_cast
还有一个额外的好处,即如果失败(即,如果bp
实际上没有指向C
),它会返回 NULL。它的缺点是性能成本较低(static_cast
在运行时实际上是免费的)。If you know for certain that you have a
B*
that points to aC
object, you can use a pair ofstatic_cast
s:The only way to cast across the inheritance hierarchy is to use
dynamic_cast
, which requires that the type is polymorphic (that is, your class must have at least one virtual member function; since your base class destructors should bevirtual
, this usually isn't a problem):dynamic_cast
has the added benefit that if it fails (that is, ifbp
doesn't actually point to aC
), it returns NULL. It has the disadvantage of a slight performance cost (static_cast
is effectively free at runtime).该代码
有效,因为 C 已经是 A,因此分配有效。
The code
is valid since C is already an A, so the assignment is valid.
如果 C 继承自 A,如您所示,则 C* 指针应该可以隐式转换为 A* 指针。是否有可能你没有包含类C的声明,所以编译器不知道这种继承关系?或者实际上存在与您的问题中给出的不同的继承关系?一些代码将有助于诊断这个问题。
编辑
根据您问题的更新版本:
If C inherits from A as you have shown, then a C* pointer should be implicitly convertible to an A* pointer. Is it possible that you haven't included the declaration of class C, so that the compiler isn't aware of this inheritance relationship? Or that there is actually a different inheritance relationship than that given in your question? Some code would be helpful in diagnosing this problem.
Edit
Based on the updated version of your question: