No appropriate default constructor available in struct with glm vectors

為{幸葍}努か 提交于 2019-12-11 10:29:31

问题


in .h:

enum collisionType {AB, BA, AoverB, AunderB};

struct Collision {
public:
    collisionType type;
    glm::vec2 point1;
    glm::vec2 point2;

    Collision(enum collisionType, glm::vec2, glm::vec2);
};

in .cpp:

Collision::Collision(enum collisionType collisType, glm::vec2 p1, glm::vec2 p2) : type(collisType), point1(p1), point2(p2)
{

}

using it

std::vector<Collision> collisions;

glm::vec2 point1(11.0, 12.0);
glm::vec2 point2(12.0, 13.0);

collisions.push_back(Collision(AoverB, point1, point2));

Getting error C2512: 'Collision' : no appropriate default constructor available, why?


回答1:


You can read here the requirements for a type T to be well suited for std::vector.
Default-constructible is not listed there.

I also tried compiling this minimal code sample, in which X doesn't have a default constructor, and it compiles fine with MSVC:

#include <vector>

struct X {
    X(int a, int b) : A(a), B(b) {}
    int A;
    int B;
};

int main() {
    std::vector<X> v;
    v.push_back(X(10,20));
}

So, the problem must be elsewhere in your code.

Anyway, you may want to add a constructor with no arguments to make your Collission class "default-constructible", and make the compiler happy:

struct Collision {

    // Default constructor.
    // Initialize data members to some init values.
    Collision() {
        ...
    }

PS Note that struct in C++ is equivalent to class { public: ..., so you can omit the public: line in your code: it's implied by the use of the keyword struct.




回答2:


The following code compiles fine, it's something else that is the problem.

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

enum collisionType {AB, BA, AoverB, AunderB};

struct Collision {
public:
    collisionType type;
    glm::vec2 point1;
    glm::vec2 point2;

    Collision(enum collisionType, glm::vec2, glm::vec2);
};

Collision::Collision(enum collisionType collisType, glm::vec2 p1, glm::vec2 p2) : type(collisType), point1(p1), point2(p2)
{

}

int main()
{
    std::vector<Collision> collisions;

    glm::vec2 point1(11.0, 12.0);
    glm::vec2 point2(12.0, 13.0);

    collisions.push_back(Collision(AoverB, point1, point2));
}


来源:https://stackoverflow.com/questions/23018536/no-appropriate-default-constructor-available-in-struct-with-glm-vectors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!