# C 多重繼承與void*指標轉換問題

C 支援多重繼承，然而多重繼承可能會導致一些奇怪的問題，我前段時間遇到一個指標轉換問題，非常典型。

``````#include <iostream>
using namespace std;
class IA
{
public:
virtual ~IA(){}
virtual void a() = 0;
};
class IB
{
public:
virtual ~IB(){}
virtual void b() = 0;
};
class CMulti : public IA, public IB
{
public:
CMulti(){}
~CMulti(){}
void a(){ cout << "C::a()" << endl; }
void b(){ cout << "C::b()" << endl; }
};
void testCastA(void *p)
{
cout << "cast from void*(" << p << ")to IA*:  ";
IA *a = (IA *)p;
a->a();
}
void testCastB(void *p)
{
cout << "cast from void*(" << p << ")to IB*:  ";
IB *b = (IB *)p;
b->b();
}
int _tmain(int argc, _TCHAR* argv[])
{
CMulti * c = new CMulti;
cout << "cast to void*, then to IA or IB:" << endl;
testCastA((void*)c);
testCastB((void*)c);
cout << endl;
cout << "static_cast to void*, then to IA or IB:" << endl;
testCastA((void*)static_cast<IA*>(c));
testCastB((void*)static_cast<IB*>(c));
cout << endl;
cout << "dynamic_cast to void*, then to IA or IB:" << endl;
testCastA((void*)dynamic_cast<IA*>(c));
testCastB((void*)dynamic_cast<IB*>(c));
return 0;
}
``````

• 強制轉換為void*
• 先static_cast再強制轉換為void*
• 先dynamic_cast再強制轉換為void*

（32位程式）執行的結果如下圖所示：