简体   繁体   English

将class作为函数参数传递时C ++不完整类型错误

[英]C++ incomplete type error when passing class as function parameter

I'm trying to use the following code, in a header file, to define a class and a function which takes a vector of pointers to this class as a parameter. 我正在尝试在头文件中使用以下代码来定义一个类和一个函数,该函数将指向此类的指针作为参数。 However, on compilation I get an incomplete type error. 但是,在编译时,我得到一个不完整的类型错误。

    #ifndef OBJECTS_H
    #define OBJECTS_H

    #include <glm/glm.hpp>
    #include <vector>

    struct Shape {
        glm::vec3 emission;
        float shininess;
        glm::vec3 Ka;
        glm::vec3 Ks;
        glm::vec3 Kd;

        Shape(glm::vec3 emission, float shininess, glm::vec3 Ka, glm::vec3 Ks, glm::vec3 Kd);
        float intersects(const glm::vec4 start, const glm::vec4 direction);
        virtual glm::vec4 randomPoint();
        virtual glm::vec4 getNormal(const glm::vec4 &p);
        virtual bool isLight();
    };

    void LoadModel(vector<Shape *> &scene, const char *path);

    #endif

Giving the error: 给出错误:

error: incomplete type is not allowed
      void LoadModel(vector<Shape *> &scene, const char *path);

Why is this error occurring, and what is the correct way to write this code? 为什么会出现此错误,编写此代码的正确方法是什么?

Change your function declaration to properly scope the std::vector 更改函数声明以正确调整std::vector范围

void LoadModel(std::vector<Shape *> &scene, const char *path);

If that doesn't fix it, then the error is about Shape . 如果这不能解决问题,则错误与Shape有关。 You need to make sure that at the definition of function LoadModel the compiler has the complete definition of class Shape if that function requires access to any of its data members. 您需要确保在函数LoadModel的定义中,如果该函数需要访问其任何数据成员,则编译器具有类Shape的完整定义。

Vectors, like all other standard library containers, are in the std namespace. 与所有其他标准库容器一样,向量位于std命名空间中。 Therefore, you should refer to it as std::vector since you don't have the line using namespace std; 因此,您应该将它称为std::vector因为您没有using namespace std;的行using namespace std; .

When I encounter these seemingly obscure errors, I try to remove the complexity in a few additional versions of the code. 当我遇到这些看似晦涩难懂的错误时,我会尝试去除一些其他版本的代码中的复杂性。

In this case, I'd create a few additional function declarations right ahead of the one with the problem: 在这种情况下,我会在问题出现之前创建一些额外的函数声明:

LoadShape(Shape, const char*); LoadShape(vector<char>, const char*);

That would show the same error for the vector<char> param, providing a clue... Obviously char wouldn't be an incomplete type so the issue is with vector and, in general, my errors in using STL types are related to either namespace issues or template-related voodoo. 这将为vector<char> param显示相同的错误,提供一个线索......显然char不是一个不完整的类型所以问题是vector ,一般来说,我使用STL类型的错误与命名空间问题或与模板相关的巫术。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM