c++ - 自定义对象的 vector

标签 c++ object inheritance vector sfml

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

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

在下面的代码中, vector 在 Explosion.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();
};

粒子.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();
};

爆炸.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*,因此 前向声明 就足够了。

Explosion.h

class Particle; // forward declaration of Particle

class Explosion {
// ...
};

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

关于c++ - 自定义对象的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20620099/

相关文章:

javascript - 如何将对象插入为面板项目

c++ - 对象值不能改变

javascript - 如何使用定制器_cloneDeepWith_并添加属性

JavaScript 继承

java - 使用子类的类型或其父类(super class)的类型创建子类对象

c++ - 如何获取函数返回类型的模板成员的取消引用类型

C++:传递和返回指向数组的指针——代码不工作

c++ - QGraphicsView 不显示在 mainWindow 中

c++ - Java JNI 包装器工具

C++单例继承问题