C++ 自定义对象的向量

C++ 自定义对象的向量,c++,object,inheritance,vector,sfml,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中定义 第h部分: Particle.cpp: #

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

error C2976: 'std::vector' : too few template arguments
error C2065: 'Particle' : undeclared identifier
error C2059: syntax error : '>'
在下面的代码中,向量在Explosion.h中定义

第h部分: Particle.cpp:
#包括
#包括“Particle.h”
粒子::粒子(浮点x、浮点y、浮点vx、浮点vy、sf::颜色){
//继承的
此->设置位置(x,y);
这->设置半径(5);
此->设置填充颜色(颜色);
//玩家定义变量
这->速度=(浮动).05;
这->活着=真;
这->vx=vx;
这个->vy=vy;
}
粒子::~Particle(){
}
爆炸。h:
static const int NUM_PARTICLES=6;
#布拉格语一次
班级爆炸{
公众:
向量粒子;
布尔活着;
爆炸();
~Explosion();
};
Explosion.cpp:
#包括
#包括“Particle.h”
#包括“爆炸.h”
爆炸::爆炸(){
这->活着=真;
//将粒子添加到向量
对于(int i=0;i粒子。推回(新粒子(0,0,0,0,sf::Color::Red));
}
}
爆炸::~爆炸(){
}

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

你需要告诉<代码>爆炸。h < /代码>什么是<代码>粒子< /代码>是。< /p> 在这种情况下,
Explosion.h
使用的是
Particle*
,因此向前宣布就足够了

爆炸.h

class Particle; // forward declaration of Particle

class Explosion {
// ...
};

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

是否需要前向声明?它看起来就像是
爆炸。h
需要
#包含“Particle.h”“
。两种方法都可以。随着代码库的增长,转发声明将成为首选,因为减少直接包含的数量可以显著减少构建时间;支持无泄漏智能pointers@ssell:您可能会说,“是否需要
包含
文件?它看起来像
爆炸。h
只需要向前声明类。”@Mitch:我建议您阅读更准确的内容。C++11的标准智能指针可以很好地存储在容器中。(2011年之前不是这样,但希望您正在学习现代C++)。
#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() {
}
static const int NUM_PARTICLES = 6;

#pragma once
class Explosion {
public:
    std::vector<Particle*> particles;
    bool alive;
    Explosion();
    ~Explosion();
};
#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() {
}
class Particle; // forward declaration of Particle

class Explosion {
// ...
};