存储所有 class 个实例的向量,并调用它们的成员函数

Storing a vector of all class instances, and calling their member functions

如何创建一个向量来存储 class 的所有实例?那么我该如何遍历它们并调用它们的成员函数之一呢?

这是我一直在尝试做的事情的浓缩示例。

#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 成员函数有效,如果我使用例如播放器->绘制。我要么搞砸了向量或迭代器,要么两者都搞砸了,我不知道如何修复它。我试过使用引用和指针,我认为这是应该做的,但每当我尝试这样做时,我都会遇到无法修复的错误。

更新: 我感谢所有的帮助,我学到了很多东西。但是我的 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;

自 c++ 11 以来使用 for 循环的更简单方法:

for( auto & entity : entities) {
     entity.Draw();
}

您想要 iter != entities.end(); 而不是 <。此外,在此代码示例中,您忘记了 Draw.

之后的括号

renderEntities() 不执行任何操作,因为您没有向 vector 添加任何 Entity 对象。当您声明 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 中,handle_input() 范围内没有 entity 变量,因此调用 entity.Draw() 不应该编译。

不过,真正的大错误在 entity.h。不要在该文件中将 entities 变量声明为 static!这会导致 每个 .cpp #include 是你的 entity.h 文件它自己的副本多变的。这意味着 main.cppentity.cpp 正在对 单独的 std::vector 对象 进行操作!这就是为什么你看到 entitiesmain.cpp 中总是空的 - Entity 对象永远不会被添加到存在于 main.cpp 中的 std::vector,只会添加到std::vector 存在于 entities.cpp.

你需要将实际的std::vector变量移动到entity.cpp中(没有static),然后在entity.h中声明变量为extern所以您的所有 .cpp 文件都可以访问和共享 单个变量 .

试试这个:

entity.h

#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.cpp

#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());
}

...

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

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

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 的向量,您需要确保循环遍历向量并在调用 [= 之前​​的某个时刻删除实体32=]() 否则你会发生内存泄漏。

最后一个示例的好处是,如果您稍后重新组织代码以拥有其他 类 extend 实体以提供它们自己的绘制行为,您的向量仍将是能够存储指向所有这些新 类 的指针并调用它们的 Draw() 方法。

这是一个例子。

#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;
}