自定义对象传染媒介

时间:2013-12-16 20:18:26

标签: c++ object inheritance vector sfml

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

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

在下面的代码中,向量在Explosion.h中定义。

Particle.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() {
}

Explosion.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 ++对我来说是相当新的。

1 个答案:

答案 0 :(得分:7)

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

在这种情况下,Explosion.h正在使用Particle*,因此转发声明就足够了。

<强> Explosion.h

class Particle; // forward declaration of Particle

class Explosion {
// ...
};

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

相关问题