c++ - 结构的“不完整类型”

标签 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;

};

在另一个 .cpp 文件中,我在 typedef 命名空间中声明了 Particle。我想要做的是实例化 Particle 结构并将它们推送到一个 vector 中。因为我有一个空的构造函数,所以我相信只用 Particle() 实例化应该可以。但是,我无法这样做,因为编译认为粗体行中存在“不允许的不完整类型”错误。 particles.push_back(Particle());

#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());
    }


}

解决方案

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

typedef struct Y Particle;

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

Structure, union, or enumerations that have no definition

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

最佳答案

你的 typedef不需要、不需要和破坏东西。事实上,typedef struct Particle Particle;是C主义。在 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{});
}

Live demo .

关于c++ - 结构的“不完整类型”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53778254/

相关文章:

android - 在NDK w/gradle上编译两个项目,其中一个依赖另一个的binary

c++ - 在 char 数组中查找不重复的字母。我的程序运行错误。需要帮忙

c++ - 使用 C++ 或 C 访问应用程序的 COM 接口(interface)

c++ - 不完整的类 : Convert void* to pointer to class type via dynamic_cast

c++ - 为什么内联声明不是不完整的类型?

c++ - C++中最小堆的比较器

c++ - 直接减去两个 vector<point2f>

c - 声明但未定义的函数的返回类型和参数中的不完整类型

c++ - 初始化一个包含自身 vector 的结构

c++ - CRTP -- 访问不完整的类型成员