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
?
If you know for certain that you have a B*
that points to a C
object, you can use a pair of static_cast
s:
B* bp = new C();
C* cp = static_cast<C*>(bp);
A* ap = static_cast<A*>(cp);
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 be virtual
, this usually isn't a problem):
B* bp = new C();
A* ap = dynamic_cast<A*>(bp);
dynamic_cast
has the added benefit that if it fails (that is, if bp
doesn't actually point to a C
), it returns NULL. It has the disadvantage of a slight performance cost (static_cast
is effectively free at runtime).
The code
class A
{
};
class B
{
};
class C : public A, public B
{
};
int main() {
C c;
A *a = &c;
}
is valid since C is already an A, so the assignment is valid.
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:
// Converts b to type A*, but only if it is actually
// of type C; otherwise, returns NULL
A* convertBtoAviaC(B* b) {
C* c = dynamic_cast<C*>(b);
return c; // note may be NULL, if b is not a C
}
精彩评论