无效指针:如何用作通用班指针
Void Pointers : how to use as a general class pointer?
我有两个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和classBclass ClassA: public Base
{
void GetPosition();
}
class ClassB: public Base
{
void GetPosition();
}
然后在您的程序中而不是声明void*,使用base*;
Base* generic_pointer;
然后,而不是铸造
generic_pointer->GetPosition();
相关文章:
- 在 C++ 中传递字符串时指针无效
- free():仅在一种情况下指针无效
- free():实现矢量擦除()时的指针无效
- free():添加字符串时指针无效
- C++ ecliipse free():函数末尾的指针无效
- C++ 指针无效函数问题
- 将 boost::object_pool 与矢量一起使用时指针无效
- free():矢量 C++ 的指针无效<vec4i>
- omnet++free():指针无效,错误134/139
- 在OpenCV中调用stereoRectify会导致异常:帧指针无效
- 销毁和重新创建一个对象会使指向该对象的所有指针无效吗
- 用户定义类中的Null指针无效
- 删除指向类的指针无效
- 运行GTest时指针无效
- C++错误消息:指针无效
- 可以std::string reconfiguration使指向堆的指针无效
- 为什么删除指向指针向量的指针会导致指针无效
- MPI_scatter:缓冲区指针无效
- mmap 错误:分段错误/指针无效错误
- 返回 std::string 时指针无效(libc 如此说)