1

这是我的问题,如果我通过函数将一个变量从 A 类传递给 B 类,然后在 B 类中将该变量传递给其他函数进行测试,那么它工作正常。但是,如果我将变量从 A 传递给 B,然后尝试将其分配给 B 类中的变量,它会无缘无故地给出错误

//Globals.h
enum TypeofObject { CIRCLE, SQUARE, RECTANGLE, DIAMOND };

//Object.h
#include "Globals.h"
class Object
{
    void Update();
private:
    TypeofObject currentObject;
    CollisionDetection * gameCollision;
};
//Object.cpp
void Object::Update()
{
    //Do stuff here
    gameCollision -> testCollision(currentObject);
}

//CollisionDetection.h
#include "Globals.h"
class CollisionDetection
{
public:
    void testCollision(TypeofObject currentObject);
private:
    void checkObjects(TypeofObject currentObject);
    TypeofObject currentObject;
}

//CollisionDetection.cpp
void CollisionDetection::testCollision(TypeofObject curObject)
{
    currentObject = curObject; //<- If I have this then it gives access violation error

    checkObjects(curObject); //<- Passing it from one function to the next works 
                             //fine but I want to assign it to currentObject so
                             //it doesnt need to be passed
}
4

1 回答 1

2

我认为这里的问题是Object::gameCollision尚未初始化。该CollisionDetection::testCollision函数被正确调用是因为您可以将成员函数想象为带有额外隐藏参数的常规函数​​:

void CollisionDetection_testCollision(CollisionDetection *this,
                                      TypeOfObject curObject);

给定您的定义,该函数将正确运行,直到this访问点:

currentObject = curObject; // this->currentObject = curObject

上面的行试图在this对象的偏移处设置一些内存。如果this未正确初始化,该函数将因访问冲突而失败。

我认为这checkObjects(curObject)不会失败,因为您没有访问CollisionDetection该函数中的任何数据成员。

于 2013-06-01T14:04:24.090 回答