存储所有类实例的向量,并调用其成员函数

时间:2018-06-07 00:23:50

标签: c++ iterator instances member-functions entity-component-system

如何创建存储类的所有实例的向量?然后我如何迭代它们并调用它们的一个成员函数?

以下是我一直在努力做的一个浓缩的例子。

#include <vector>

struct Entity{

    Entity::Draw(){
        // do drawing things
    }
};

static std::vector<Entity> entities;

Entity player;
Entity enemy;

void renderEntities() {

    for (std::vector<Entity>::iterator iter = entities.begin();
            iter < entities.end();
            iter++) {

        iter->Draw; // Error in the example. I'm using Draw(); in the actual code.
}

但是renderEntities()没有做任何事情。 Draw成员函数有效,如果我使用例如播放器 - &GT;绘制。我要么搞砸了矢量或者是迭代器,要么两者兼而有之,我无法弄清楚如何修复它。我已经尝试过使用引用和指针,我认为这是要做的事情,但每当我尝试时,我都会收到我无法解决的错误。

更新: 我很感激所有的帮助,我正在学习很多东西。但是我的render_entities函数仍然没有做任何事情。这是所有代码。

以terminal_开头的任何函数调用都来自BearLibTerminal库。

的main.cpp

#include <BLT/BearLibTerminal.h>
#include <iostream>
#include <string.h>
#include <vector>

#include "entity.h"

const int WindowSizeX{50};
const int WindowSizeY{20};
const std::string Title{"BLT Test"};
const std::string Font{"../res/SourceCodePro-Regular.ttf"};
const int FontSize{24};

bool quit_game{false};

static Entity player;
static Entity enemy;

void initialize();
void handle_input(int key, Entity &entity);
void draw_player(int x, int y, const char *symbol);
void render_entities();
void clear_entities();

int main() {

    initialize();

    while (!quit_game) {

        terminal_refresh();

        int key{terminal_read()};

        if (key != TK_CLOSE) {

            handle_input(key, player);
        }

        else {

            quit_game = true;
            break;
        }

        clear_entities();
    }

    terminal_close();

    return 0;
}

void initialize() {

    terminal_open();

    std::string size{"size=" + std::to_string(WindowSizeX) + "x" +
                     std::to_string(WindowSizeY)};
    std::string title{"title='" + Title + "'"};
    std::string window{"window: " + size + "," + title};

    std::string fontSize{"size=" + std::to_string(FontSize)};
    std::string font{"font: " + Font + ", " + fontSize};

    std::string concatWndFnt{window + "; " + font};
    const char *setWndFnt{concatWndFnt.c_str()};

    terminal_set(setWndFnt);
    terminal_clear();

    player.x = 0;
    player.y = 0;
    player.layer = 0;
    player.symbol = "P";
    player.color = "green";

    enemy.x = 10;
    enemy.y = 10;
    enemy.layer = 0;
    enemy.symbol = "N";
    enemy.color = "red";
}

void handle_input(int key, Entity &entity) {

    int dx{0};
    int dy{0};

    switch (key) {

        case TK_LEFT:
        case TK_H:
            dx = -1;
            dy = 0;
            break;

        case TK_RIGHT:
        case TK_L:
            dx = 1;
            dy = 0;
            break;

        case TK_UP:
        case TK_K:
            dx = 0;
            dy = -1;
            break;

        case TK_DOWN:
        case TK_J:
            dy = 1;
            dx = 0;
            break;

        case TK_Y:
            dx = -1;
            dy = -1;
            break;

        case TK_U:
            dx = 1;
            dy = -1;
            break;

        case TK_B:
            dx = -1;
            dy = 1;
            break;

        case TK_N:
            dx = 1;
            dy = 1;
            break;

        case TK_ESCAPE:
            quit_game = true;
            break;
    }

    player.Move(dx, dy);

    if (player.x > WindowSizeX - 1) {

        player.x = WindowSizeX - 1;
    }
    else if (player.x < 0) {

        player.x = 0;
    }

    if (player.y > WindowSizeY - 1) {

        player.y = WindowSizeY - 1;
    }
    else if (player.y < 0) {

        player.y = 0;
    }

    player.Draw(); // This works.
    enemy.Draw();  // So do this.
    entity.Draw(); // This draws only player.
    render_entities(); // This doesn't do anything.

    // Player X and Y are printed out correctly, Entities is always 0.
    std::cout << "Player X: " << player.x << std::endl;
    std::cout << "Player Y: " << player.y << std::endl;
    std::cout << "Entities: " << entities.size() << std::endl;
}

void render_entities() {

    for (auto entity : entities) {
        entity->Draw();
    }
}

void clear_entities() {

    for (auto entity : entities) {
        entity->Clear();
    }
}

entity.h

#ifndef ENTITY_H_
#define ENTITY_H_

struct Entity {

    int x;
    int y;
    int layer;
    const char *symbol;
    const char *color;

    Entity();
    ~Entity();

    void Move(int dx, int dy);
    void Draw();
    void Clear();
};

static std::vector<Entity *> entities;

#endif /* ENTITY_H_ */

entity.cpp

#include <BLT/BearLibTerminal.h>
#include <vector>
#include <algorithm>
#include "entity.h"

Entity::Entity() {

    entities.push_back(this);
}

// Entity(const Entity &) : Entity() {}
// I get an "expected unqualified-id" when I uncomment this. Why?

Entity::~Entity() {

    auto iter = std::find(entities.begin(), entities.end(), this);

    if (iter != entities.end())
        entities.erase(iter);
}

void Entity::Move(int dx, int dy) {

    this->x += dx;
    this->y += dy;
}

void Entity::Draw() {

    terminal_layer(this->layer);
    terminal_color(color_from_name(this->color));
    terminal_print(this->x, this->y, this->symbol);
}

void Entity::Clear() {

    terminal_layer(this->layer);
    terminal_print(this->x, this->y, " ");
}

在main.cpp中,在handle_input()的底部你会看到......

    player.Draw(); // This works.
    enemy.Draw();  // So do this.
    entity.Draw(); // This draws only player.
    render_entities(); // This doesn't do anything.

    // Player X and Y are printed out correctly, Entities is always 0.
    std::cout << "Player X: " << player.x << std::endl;
    std::cout << "Player Y: " << player.y << std::endl;
    std::cout << "Entities: " << entities.size() << std::endl;

5 个答案:

答案 0 :(得分:2)

renderEntities()没有做任何事情,因为您没有向Entity添加任何vector个对象。当您声明playerenemy个对象时,它们只是在内存中闲置,它们不会自动添加到vector。您需要明确添加它们,例如通过调用entities.push_back()

我建议使用Entity构造函数和析构函数自动更新vector,而不是必须记住手动执行。这样,每个Entity对象都由renderEntities()计算,例如:

#include <vector>
#include <algorithm>

struct Entity;
static std::vector<Entity*> entities;

struct Entity
{    
    Entity()
    {
        entities.push_back(this);
    }

    Entity(const Entity &)
        : Entity()
    {
    }

    ~Entity()
    {
        auto iter = std::find(entities.begin(), entities.end(), this);
        if (iter != entities.end())
            entities.erase(iter);
    }

    void Draw()
    {
        // do drawing things
    }
};

Entity player;
Entity enemy;

void renderEntities()
{
    for (auto *entity : entities)
    {
        entity->Draw();
    }
}

Live Demo

更新:看到完整的代码后,我发现您仍然犯了一些错误。

main.cpp中,entity范围内没有handle_input()变量,因此调用entity.Draw()不应该编译。

但真正的大错误在于entity.h。请勿在该文件中将entities变量声明为static!这会导致每个 .cpp #include您的entity.h文件获取自己的变量副本。这意味着main.cppentity.cpp正在单独的std::vector个对象上运行!这就是entitiesmain.cpp始终为空的原因 - Entity对象永远不会添加到std::vector中存在的main.cpp,只会添加到std::vector entities.cpp中存在的std::vector

您需要将实际entity.cpp变量移至static(不含extern),然后在entity.h中将变量声明为.cpp,以便全部您的#ifndef ENTITY_H_ #define ENTITY_H_ #include <vector> #include <string> struct Entity { int x = 0; int y = 0; int layer = 0; std::string symbol; std::string color; Entity(); Entity(const Entity&); ~Entity(); Entity& operator=(const Entity&) = default; ... }; extern std::vector<Entity *> entities; // <-- extern, NOT static! #endif /* ENTITY_H_ */ 个文件可以访问和共享单个变量

请改为尝试:

entity.h

#include <BLT/BearLibTerminal.h>
#include <vector>
#include <algorithm>
#include "entity.h"

std::vector<Entity *> entities; // <-- real variable, also NOT static!

Entity::Entity() {
    entities.push_back(this);
}

Entity::Entity(const Entity &src) : Entity() {
    *this = src;
}

Entity::~Entity() {
    auto iter = std::find(entities.begin(), entities.end(), this);
    if (iter != entities.end())
        entities.erase(iter);
}

...

void Entity::Draw() {
    terminal_layer(layer);
    terminal_color(color_from_name(color.c_str()));
    terminal_print(x, y, symbol.c_str());
}

...

entity.cpp

{{1}}

答案 1 :(得分:1)

您需要ListBox1.Font = New Font(ListBox1.Font.FontFamily, ListBox1.Font.SizeInPoints + 2, ListBox1.Font.Style, GraphicsUnit.Point) ListBox1.DrawMode = DrawMode.Normal ListBox1.DrawMode = DrawMode.OwnerDrawVariable ListBox1.Height = '[OriginalHeight] ListBox1.Update() 而不是iter != entities.end();。此外,在此代码示例中,您忘记了<之后的括号。

答案 2 :(得分:0)

从c ++ 11开始使用for循环更容易:

delete from dummy2 d1 where d1.num='7' and time in (select time from dummy2 d2 where d2.num='5') ;

答案 3 :(得分:0)

有几种方法可以做到这一点,我会将它们从最差到最好排名(不是说你的方式很糟糕,只是在这种情况下有更好的方法)。

您的代码存在问题iter->Draw; - &gt;这实际上并不是在调用函数,所以它应该是:

for (std::vector<Entity>::iterator iter = entities.begin();
        iter < entities.end();
        iter++) {
    iter->Draw(); // Notice I added ()
}

但是,有一种更好的方法可以做同样的事情:

// Entity & is important so that a copy isn't made
for (Entity & entity : entities) {
    entity.Draw();
}

现在是上述版本的等效(但略微更好):

// Notice the use of auto!
for (auto & entity : entities) {
    entity.Draw();
}

最后,如果你以后决定需要它作为指针的矢量,你可以:

static std::vector<Entity *> entities;

static Entity * player = new Entity();
static Entity * enemy = new Entity();

...

for (Entity * entity : entities) { // You could also use (auto entity : entities)
    entity->Draw();
}

在这种情况下,因为它是raw pointers而不是smart pointers的向量,所以在调用entities.clear之前,您需要确保循环遍历向量并删除某些实体。 )或者你会有内存泄漏。

关于最后一个例子的好处是,如果你以后重新组织你的代码以拥有其他类extend实体以便提供他们自己的Draw行为,你的向量仍然可以存储指向所有的指针这些新类并调用它们的Draw()方法。

答案 4 :(得分:0)

这是一个例子。

#include <iostream>
#include <string>
#include <vector>

using namespace std;

struct Entity {
    Entity(string _name):name(_name){} 
    void Draw(){
        // do drawing things
        cout << name << "::Draw" << endl;
    }
    private:
    string name;
};

static std::vector<Entity *> entities;

static Entity * player = new Entity("Player");
static Entity * enemy = new Entity("Enemy");

void renderEntities() 
{
    for( auto & entity : entities){
       entity->Draw();
    }
}

int main()
{
   entities.push_back(player);
   entities.push_back(enemy);

   renderEntities();

   return 0;
}