C++ 错误:使用重载运算符'*';含糊不清
当我尝试用c++编译此源代码时:C++ 错误:使用重载运算符'*';含糊不清,c++,pointers,vector,reference,C++,Pointers,Vector,Reference,当我尝试用c++编译此源代码时: void ParticleSystem::setState(std::vector<Vec2f>& statesVector) { std::vector<Vec2f> pState(2); for (int i = 0; i < 2*np; i += 2) { pState[0] = *statesVector[i]; pState[1] = *(statesVector[i
void ParticleSystem::setState(std::vector<Vec2f>& statesVector)
{
std::vector<Vec2f> pState(2);
for (int i = 0; i < 2*np; i += 2) {
pState[0] = *statesVector[i];
pState[1] = *(statesVector[i+1]);
(*particles[i/2]).setState(pState);
}
}
void ParticleSystem::setState(std::vector和statesVector)
{
std::向量pState(2);
对于(int i=0;i<2*np;i+=2){
pState[0]=*statesVector[i];
pState[1]=*(statesVector[i+1]);
(*粒子[i/2])。设置状态(pState);
}
}
我得到以下错误:
ParticleSystem.cpp:110:15: error: use of overloaded operator '*' is ambiguous (operand type
'value_type' (aka 'gfx::TVec2<float>'))
pState[0] = *statesVector[i];
^~~~~~~~~~~~~~~~
ParticleSystem.cpp:110:15: note: built-in candidate operator*(float *)
ParticleSystem.cpp:110:15: note: built-in candidate operator*(const float *)
ParticleSystem.cpp:111:15: error: use of overloaded operator '*' is ambiguous (operand type
'value_type' (aka 'gfx::TVec2<float>'))
pState[1] = *(statesVector[i+1]);
ParticleSystem.cpp:110:15:错误:重载运算符“*”的使用不明确(操作数类型
“值类型”(又名“gfx::TVec2”)
pState[0]=*statesVector[i];
^~~~~~~~~~~~~~~~
ParticleSystem.cpp:110:15:注意:内置候选运算符*(float*)
ParticleSystem.cpp:110:15:注:内置候选运算符*(常量浮点*)
ParticleSystem.cpp:111:15:错误:重载运算符“*”的使用不明确(操作数类型
“值类型”(又名“gfx::TVec2”)
pState[1]=*(statesVector[i+1]);
我已经在论坛中查找了错误,并遵循了一些步骤,但我始终无法使其正常工作。此外,我还试图理解错误注释中的解释,但我无法理解。
我真的希望有人能帮助我
最后,如果有人对这个问题的评价是否定的,请至少解释一下原因。问题是你不理解引用的语法。虽然使用
&
声明引用,但使用它的方式与使用实际变量的方式相同,而不像指针,这意味着您不能在其上使用运算符*
(除非它是指针类型上的引用)。使用*
运算符产生的效果与在正则变量上使用它时的效果相同
您可以通过如下方式删除代码中的*
来解决问题:
pState[0] = statesVector[i];
pState[1] = statesVector[i+1];
particles[i/2].setState(pState);
如果在
Vec2f
类中定义了operator*
,并使其返回Vec2f
,则代码可以按原样编译。但是,从语义的角度来看,这没有什么意义(未引用的值不应给出相同类型的内容),因此这不是解决问题的方法。是函数指针吗?statesVector[i]
的计算结果为Vec2f&
。没有为Vec2f
定义一元运算符*
。目前还不清楚您打算在这条线路上做什么。仅供参考,operator[]
比operator*
更重要。首先,你可能应该分清你真正想做什么。请在你的问题中指出什么是Vec2f
。有许多工具包都使用这个名称声明类型,但您没有给出具体的指示。如果你只想影响你的statesVector
的值,你不需要*
。引用不需要*
运算符来获取值。@meneldal,这就是答案。谢谢大家!!