无效指针:如何用作通用班指针

Void Pointers : how to use as a general class pointer?

本文关键字:指针 无效 何用作      更新时间:2023-10-16

我有两个CPP类,例如Classa和ClassB。我有两个指向该课程相应指向的指针,可以说Pointera和Pointerb。现在,我有一个通用的void*指针,我想根据某些条件指向classa或classB。在这种情况下,获得错误错误C2227:" -> getPosition"的左侧必须指向class/struct/union/ension类型类型是'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(); 
   //*****************************************************************************

}

a void指针没有一种称为GetPosition的方法,并且指针本身不可能知道它指向您的一个类,因为它存储了内存地址,而不是类型。您需要使用演员:

reinterpret_cast<ClassA*>(generic_pointerAorB)->GetPosition();

但是,老实说,您应该做其他事情 - 从具有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();

您不能取消void *类型。

原因很简单,编译器无法通过void *键入generic_pointer实际上指向的内存(在您的情况下)。

以这种方式使用它:

((ClassA*)generic_pointer)->GetPosition();

或等效,

((ClassB*)generic_pointer)->GetPosition();

如果您使用的是C ,那么一种更好的方法是定义虚拟基类

class Base
{
public:
   virtual void GetPosition();
};

然后从base

中得出classa和classB
class ClassA: public Base
{
   void GetPosition();
}
class ClassB: public Base
{
   void GetPosition();
}

然后在您的程序中而不是声明void*,使用base*;

Base* generic_pointer;

然后,而不是铸造

generic_pointer->GetPosition();