问题描述
我有一个带有以下声明的类:
I have a class with the following declarations:
class IcoSphere
{
[...]
private:
int _addVertex(const glm::vec3 &p);
int addVertex(glm::vec3 p);
int addVertex(const glm::vec3 &&p);
[...]
};
然后,我像这样调用addVertex":
Then, I'm calling 'addVertex' like so:
IcoSphere sphere;
double t = (1.0 +sqrt(5.0)) /2.0;
sphere.addVertex(glm::vec3(-1,t,0));
'addVertex' 的参数显然不是引用,但 g++ 编译器会抛出以下错误:
The argument for 'addVertex' is obviously not a reference, and yet the g++-compiler throws the following error:
./network/icosphere.cpp: In static member function ‘static void IcoSphere::Create(glm::vec3&, float, std::vector<glm::tvec3<float, (glm::precision)0u> >&, int)’:
./network/icosphere.cpp:46:36: error: call of overloaded ‘addVertex(glm::vec3)’ is ambiguous
sphere.addVertex(glm::vec3(-1,t,0));
^
./network/icosphere.cpp:46:36: note: candidates are:
./network/icosphere.cpp:19:5: note: int IcoSphere::addVertex(glm::vec3)
int IcoSphere::addVertex(glm::vec3 p) {_addVertex(p);}
^
./network/icosphere.cpp:20:5: note: int IcoSphere::addVertex(const vec3&&)
int IcoSphere::addVertex(const glm::vec3 &&p) {_addVertex(p);}
^
这对我来说没有多大意义,为什么认为这是一个模棱两可的电话?
This doesn't make a whole lot of sense to me, why is it considering it an ambiguous call?
推荐答案
编译器在处理函数重载解析时,首先获取所有可行的函数,然后对它们进行排序,调用排序最高的函数.
When compiler dealing with function overloading resolution, it firstly gets all the viable functions, then ranks them and call the one with highest ranking.
例如
type var;
void func(type);
void func(tpye&&);
func(var);
这两个 func 方法的排名相同.它们都是完全匹配的.不需要提升或隐式类型转换或其他任何东西.你的问题也是同样的情况.所以你可能想改变
Both of the func methods have the same ranking. They are all exact match. No promotion or implicit type cast or anything else is needed. The same case for your question. So you may want to change
int addVertex(glm::vec3 p);
到
int addVertex(const glm::vec3& p);
因为你不打算改变它.关于重载解析和右值引用重载解析的更多信息,http://www.dcs.bbk.ac.uk/~roger/cpp/week20.htm, http://yapb-soc.blogspot.com/2015/01/rvalue-references-and-function.html
because you're not aiming to change it. Some more about overload resolution and rvalue reference overload resolution, http://www.dcs.bbk.ac.uk/~roger/cpp/week20.htm, http://yapb-soc.blogspot.com/2015/01/rvalue-references-and-function.html
这篇关于带有重载 r 值引用函数的模棱两可的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!