문제

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_casts:

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
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top