传递变量时C ++访问冲突

时间:2013-06-01 13:45:00

标签: c++

继承我的问题,如果我通过函数将一个变量从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
}

1 个答案:

答案 0 :(得分:2)

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

void CollisionDetection_testCollision(CollisionDetection *this,
                                      TypeOfObject curObject);

根据您的定义,该函数将正确运行,直到访问this

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

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

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