c++ - 拥有构造函数会导致错误“错误:没有运算符“=”匹配这些操作数”
问题描述
所以,我有一个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} };
}
解决方案
您需要更多{}
'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
}
}
};
推荐阅读
- reactjs - 刷新页面后应用组件样式
- anylogic - 优先项目选择输出
- apache - 如何从链接中删除目录
- c# - 如何在 Blazor 中呈现定义为对象的组件?
- postgresql - 如何按 detection_time 从和到特定时间进行分组?在PostgreSQL中
- python - 循环解析 JSON devOps API
- javascript - unhandledPromiseRejectionWarning:TypeError:无法读取 null 的属性“密码”
- unity3d - 我想在 OntriggerEnter 上联系游戏对象的孩子
- wxpython - 漏洞?wxpython TreeCtrl.GetParent ---> 参数太多
- laravel - 如何在 laravel 中使用观察者删除多级关系数据?