自定义对象的矢量

Vector of Custom Objects

本文关键字:对象 自定义      更新时间:2023-10-16

我正在尝试创建一个在头文件中定义的自定义对象向量,然后在实际的cpp文件中初始化它们。我在Visual Studio中收到以下错误:

error C2976: 'std::vector' : too few template arguments
error C2065: 'Particle' : undeclared identifier
error C2059: syntax error : '>'

在下面的代码中,矢量在Exploration.h.中定义

粒子.h:

#pragma once
class Particle : public sf::CircleShape {
public:
    float speed;
    bool alive;
    float vx;
    float vy;
    Particle(float x, float y, float vx, float vy, sf::Color color);
    ~Particle();
};

Particle.cpp:

#include <SFML/Graphics.hpp>
#include "Particle.h"
Particle::Particle(float x, float y, float vx, float vy, sf::Color color) {
    // Inherited
    this->setPosition(x, y);
    this->setRadius(5);
    this->setFillColor(color);
    // Player Defined Variables
    this->speed = (float).05;
    this->alive = true;
    this->vx = vx;
    this->vy = vy;
}
Particle::~Particle() {
}

爆炸.h:

static const int NUM_PARTICLES = 6;
#pragma once
class Explosion {
public:
    std::vector<Particle*> particles;
    bool alive;
    Explosion();
    ~Explosion();
};

Explosion.cpp:

#include <SFML/Graphics.hpp>
#include "Particle.h"
#include "Explosion.h"
Explosion::Explosion() {
    this->alive = true;
    // Add Particles to vector
    for (int i = 0; i < NUM_PARTICLES; i++) {
        this->particles.push_back(new Particle(0, 0, 0, 0, sf::Color::Red));
    }
}
Explosion::~Explosion() {
}

我确信这里有一些根本性的错误,因为C++对我来说是相当新的。

您需要告诉Explosion.h什么是Particle

在这种情况下,Explosion.h使用Particle*,因此前向解密就足够了。

爆炸。h

class Particle; // forward declaration of Particle
class Explosion {
// ...
};

您也可以简单地使用#include "Particle.h,但是随着项目的增加,使用正向声明(而不是直接包含)可以显著减少构建时间。