为什么我的构造函数不像应有的那样初始化其超类属性?

时间:2019-12-10 15:20:44

标签: c++ inheritance

看,我有一只猫。

#pragma once
#include "../CoreComponents/MTT_GraphicalStaticObject.h"


class Cat : public MTT_GraphicalStaticObject {
public:
    Cat(int x, int y) : MTT_GraphicalStaticObject(x, y) {};
    Cat(int* x, int* y) : MTT_GraphicalStaticObject(x, y) {};

};

猫是从我的自定义类MTT_GraphicalStaticObject派生的:

#pragma once
#include "MTT_GraphicalObject.h"

class MTT_GraphicalStaticObject: public MTT_GraphicalObject {
public:

    MTT_GraphicalStaticObject() :MTT_GraphicalObject() {};
    MTT_GraphicalStaticObject(int x, int y) :MTT_GraphicalObject(x, y) {  };
    MTT_GraphicalStaticObject(int* x, int* y) : MTT_GraphicalObject(x, y) {};

    int* x = NULL; 
    int* y = NULL;

    void loadSpriteFromFilename(std::string filename);
    void render(Camera cam);


protected:
    MTT_Texture spriteTexture;
};

...并且MTT_GraphicalStaticObject源自您可以在此处看到的抽象类。

#pragma once
#include "MTT_Texture.h"
#include <string>
#include "../Graph/Camera.h"


class MTT_GraphicalObject {

public:

    MTT_GraphicalObject();
    MTT_GraphicalObject(int x, int y);
    MTT_GraphicalObject(int* x, int* y);

    int* x = NULL; 
    int* y = NULL;
    virtual void render(Camera cam) = 0;

};

但是。

当我尝试与猫玩耍时,出现了问题。 见下文:

int* in = new int(40);
Cat* cat = new Cat(in,in);
cat->loadSpriteFromFilename("Cat.png");
overworldGraphicalManager->aRandomCat = cat; 
; //My breakpoint here says that my cat x and y value are not initialized.

当我尝试这样做时也会发生同样的事情:

Cat* cat = new Cat(40,40);
cat->loadSpriteFromFilename("Cat.png");
overworldGraphicalManager->aRandomCat = cat; 
; //same result

但是,如果我这样做,它有效

int* in = new int(40);
Cat* cat = new Cat(in,in);
cat->x = in;
cat->y = in;
cat->loadSpriteFromFilename("Cat.png");
overworldGraphicalManager->aRandomCat = cat;
; //It works! But i don't want these kind of workarounds.

我的问题很简单:为什么会发生这种事情?

回答该问题将帮助我找到解决方案,以便能够以社会认可的方式初始化我的猫。

(这是初始化程序的源代码)

#include "../../Headers/CoreComponents/MTT_GraphicalObject.h"

MTT_GraphicalObject::MTT_GraphicalObject() {
    this->x = 0;
    this->y = 0;
}

MTT_GraphicalObject::MTT_GraphicalObject(int x, int y)
{
    this->x = &x;
    this->y = &y;
}

MTT_GraphicalObject::MTT_GraphicalObject(int* x, int* y)
{
    this->x = x;
    this->y = y;
}

1 个答案:

答案 0 :(得分:2)

您获取局部变量的地址:

MTT_GraphicalObject::MTT_GraphicalObject(int x, int y)
{
    this->x = &x;
    this->y = &y;
}

地址指向堆栈。离开示波器后,它会消失,因此您会有不可预测的行为。

就您而言,我认为您不需要将类成员声明为指针。

int* x = NULL; 
int* y = NULL;

查看使用int x, y作为值