首页 > 解决方案 > 拥有构造函数会导致错误“错误:没有运算符“=”匹配这些操作数”

问题描述

所以,我有一个struct网格,它包含一个包含向量的三角形的 std::vector。

template <typename T>
struct genericVec3d
{
    T x = 0, y = 0, z = 0, w = 1;

    //////constructors
    genericVec3d() {};
    genericVec3d(T _x, T _y, T _z, T _w) :x(_x), y(_y), z(_z), w(_w) {};
    genericVec3d(T _x, T _y, T _z) :x(_x), y(_y), z(_z) {};
    genericVec3d(const genericVec3d& other) : x(other.x), y(other.y), z(other.z) {};
}; 

typedef genericVec3d<float> vf3d;

struct triangle
{
    vf3d p[3];
};

struct mesh
{
    std::vector<triangle> tris;
}; 

main中,如果我尝试使用构造函数初始化网格

int main(int argc, char* argv[])
{
    mesh sheet;
    sheet.tris = { {1, 1, 1} };
    return 0;
}

no operator "=" matches these operands我收到一条错误消息sheet.tris = { {1, 1, 1} };

如果我注释掉所有的构造函数,它运行良好,但是有任何构造函数会导致错误,我不知道为什么。我需要这些构造函数才能让我的其余代码运行。我能做些什么?

可重现的代码

#include <vector>

template <typename T>
struct genericVec3d
{
    T x = 0, y = 0, z = 0, w = 1;

    //////constructors
    genericVec3d() {};
    genericVec3d(T _x, T _y, T _z, T _w) :x(_x), y(_y), z(_z), w(_w) {};
    genericVec3d(T _x, T _y, T _z) :x(_x), y(_y), z(_z) {};
    genericVec3d(const genericVec3d& other) : x(other.x), y(other.y), z(other.z) {};
};

typedef genericVec3d<float> vf3d;

struct triangle
{
    vf3d p[3];
};

struct mesh
{
    std::vector<triangle> tris;
};

int main()
{
    mesh sheet;
    sheet.tris = { {1, 1, 1} };
}

标签: c++constructor

解决方案


您需要更多{}'s,因为您刚才所做的是创建一个带有单个三角形的向量,并且该三角形试图在只有 1 个(数组)时设置 3 个变量。

    // what you have
    sheet.tris = { // vector of triangles
        { // triangle
            1, // meant to be array of vf3ds, but it's instead an int
            1, // ?
            1  // ?
        }
    };
    // what you need
    sheet.tris = { // vector of triangles
        { // triangle
            { // array of vf3ds
                { 1.f, 1.f, 1.f } // vf3ds
                // ideally two more vf3ds should be here,
                // because triangle stores an array of 3 vf3ds
            }
        }
    };

推荐阅读