Void Pointers:如何用作通用类指针?

Mav*_*ick 0 c++ pointers void-pointers

我有两个cpp类让我们说ClassA和ClassB.我有两个指针,相应地指向那些类,让我们说指针A和指针B. 现在我有一个通用的void*指针,我想根据某些条件指向ClassA或ClassB.在这种情况下获取错误错误C2227:' - > GetPosition'的左边必须指向类/ struct/union /泛型类型是'void*'.

如何避免这种错误?

ClassA { 
   void GetPosition();
}

ClassB { 
   void GetPosition();
}

main() {

   ClassA  *pointerA;
   ClassB  *pointerB;
   void    *generic_pointerAorB;

   pointerA = GetAddrOfClassA();
   pointerB = GetAddrOfClassB()

   generic_pointer = pointerA;

   //********************** error at the code below ******************************
   //error C2227: left of '->GetPosition' must point to class/struct/union/generic type. 
   //type is 'void *'

   generic_pointer->GetPosition(); 

   //*****************************************************************************



}
Run Code Online (Sandbox Code Playgroud)

Paw*_*arz 9

一个void指针没有一个调用的方法GetPosition,以及指针本身不可能知道它的指向你的类之一,因为它存储了内存地址,而不是类型.你需要使用一个演员:

reinterpret_cast<ClassA*>(generic_pointerAorB)->GetPosition();
Run Code Online (Sandbox Code Playgroud)

但说实话,你应该做一些其他的事情 - 从一些有一个virtual GetPosition()方法的基类派生类,然后声明一个指向基类的指针.

class Base{
   virtual void GetPosition();

ClassA: public Base { 
   void GetPosition();
}

ClassB: public Base { 
   void GetPosition();
}

main(){
   Base* basePointer;
   // <-- other code here
   basePointer = pointerA;
   basePointer->GetPosition();
Run Code Online (Sandbox Code Playgroud)