'不完整类型'的结构

wed*_*ran 0 c++ incomplete-type

我已经在.hpp文件中定义了一个粒子类Particle

#ifndef PARTICLE_HPP
#define PARTICLE_HPP
#include <glm/glm.hpp>
#include <GL/glew.h>
#include <GL/gl.h>

#include <vector>

struct Particle
{
    Particle()
        : m_Position(0.0f)
        , m_Velocity(0.0f)
        , m_Color(1.0f)
        , m_fRotate(0.0f)
        , m_fAge(0.0f)
        , m_fLifeSpan(0.0f)
        , m_is_alive(false)
    {}
public:
    glm::vec3   m_Position; // Center point of particle
    glm::vec3   m_Velocity; // Current particle velocity
    glm::vec4   m_Color;    // Particle color
    GLfloat     m_fRotate;  // Rotate the particle the center
    GLfloat     m_fSize;    // Size of the particle
    GLfloat     m_fAge; 
    GLfloat     m_fLifeSpan; 
    bool        m_is_alive;

};
Run Code Online (Sandbox Code Playgroud)

在另一个.cpp文件中,我在typedef命名空间中声明了Particle.我想要做的是实例化粒子结构并将它们推入向量中.因为我有一个空的构造函数,我相信只使用Particle()进行实例化应该可行.但是,我不能这样做,因为编译认为粗体线中存在"不完全类型不允许"错误. particles.push_back(颗粒());

#include "Particle.hpp"
#include <stdlib.h> //malloc
#include <iostream>

#include <GL/glew.h>
#include <GL/freeglut.h>

#include<vector>

typedef struct Particle Particle;
typedef std::vector<Particle> ParticleBuffer;
ParticleBuffer particles;


int main(){
    GLuint nr_particles = 100; 

    for (GLuint i = 0; i < nr_particles; ++i) {
        particles.push_back(Particle());
    }


}
Run Code Online (Sandbox Code Playgroud)

使用typedef省略了真正的问题,那就是

typedef struct Y Particle;
Run Code Online (Sandbox Code Playgroud)

这里没有定义Y,因为我认为它是从头文件(.hpp)中提取定义,但由于某种原因,Microsoft Visual Studio(我用来编译和构建)没有链接头文件,但没有给出任何错误.相反,它只是表现得像Y不存在,如果我们看一下'不完整类型'的定义:

没有定义的结构,联合或枚举

这个错误现在有意义了."解决方法"解决方案是使用.h文件而不是.hpp,因此它将被链接.同样正如@YSC在接受的答案中指出的那样,没有必要使用typedef,因为定义是从.h文件中正确提取的,它应该没有错误.

YSC*_*YSC 8

你的typedefs不需要,不需要,也不需要破坏.的确,typedef struct Particle Particle;是一个C-ism.在C++中,struct x {...};引入x范围中的名称,无需为其添加前缀struct.

把事情简单化:

#include <vector>

struct Particle { /* ... */ }; // in real life, this is defined in a separate file
std::vector<Particle> GlobalVariablesAreEvil;

int main()
{
    GlobalVariablesAreEvil.push_back(Particle{});
}
Run Code Online (Sandbox Code Playgroud)

现场演示.

  • s /`^ struct Particle.*`/`#include"Particle.hpp"`/ (3认同)