尝试将子指针分配给父指针向量

时间:2016-11-11 20:41:47

标签: c++ pointers vector

我遇到了一个headscratcher,因为我在编译时没有遇到任何错误,只是在运行时。这是一些示例代码:

entity.h

#ifndef ENTITY_H
#define ENTITY_H

#include <vector>
#include "component.h"

struct Entity
{   
    std::vector<Component*> components;
};

#endif

这是我的实体。我只想要它保存一个数据组件列表。

component.h

#ifndef COMPONENT_H
#define COMPONENT_H

#include <string>

struct Component
{
    std::string name;
};

#endif

这是组件的父级。我需要它,以便实体可以列出不同种类的子组件。

comp_position.h

#ifndef COMP_POSITION_H
#define COMP_POSITION_H

#include "component.h"

struct Position : Component
{
    Position(int y, int x) {this->y = y; this->x = x; name = "Position";}

    int y, x;
};

#endif

以下是其中一个组件的示例。只包含实体的2D位置。

assemblages.h

#ifndef ASSEMBLAGES_H
#define ASSEMBLAGES_H

#include "entity.h"
#include "comp_position.h"

Entity* makePlayer(int y, int x){
    Entity* player;
    player->components.push_back(new Position(y, x));
    return player;
}

#endif

这是一个集合,以便我可以轻松构建播放器类型实体。 将位置指针放入组件指针列表的那一刻是程序崩溃的地方。

main.cc

#include "assemblages.h"
#include "entity.h"

#include <iostream>

using namespace std;

int main()
{
    Entity* player = makePlayer(10, 10);

    return 0;
}

最后,这是我的主要内容,我只是尝试创建一个玩家。如上所述,在程序集中,程序崩溃了。知道我做错了什么吗?对不起,这里有很多文件,我想确保我完全代表我的实际程序,同时仍然试图尽可能地剥离。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

这一行:

Entity* player;

创建未初始化的Entity指针。它没有指向有效的对象。您需要对其进行初始化,例如:通过使用new在堆上分配对象。

请注意,将拥有的对象存储为裸指针不是一个好习惯,它很容易导致内存泄漏。改为使用unique_ptr,当指出的对象超出范围时,它将自动delete