g ++无法编译此程序,因为: "
45:20: warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:
xxx.cpp:27:15: note: candidate 1: const Point2d Point2d::operator*(float) const
const Point2d Point2d::operator*(float xy) const
xxx.cpp:45:20: note: candidate 2: operator*(double, int) <built-in>
Point2d x = xxx * 3;
&#34;
当我删除&#34; operator double()&#34;然后&#34;运营商*&#34;有效,但是可以选择立即将它们运送给运营商吗?
代码:
class Point2d {
public :
Point2d(float x, float y);
const Point2d operator*(float xy) const;
operator double(); //when I delete operator double(), then operator* works
private :
float x;
float y;
};
Point2d::operator double()
{
return sqrt((this->x * this->x) + (this->y * this->y));
}
const Point2d Point2d::operator*(float xy) const
{
return Point2d(x * xy, y * xy);
}
Point2d::Point2d(float x, float y)
{
this->x = x;
this->y = y;
}
int main()
{
Point2d xxx(3, 5.5);
Point2d x = xxx * 3;
return 0;
}
答案 0 :(得分:1)
在xxx * 3
中,编译器可以使用{{1}将3
转换为float
并使用operator*(float xy)
或将xxx
转换为double
然后使用内置乘法。
规则说这是不明确的,因此不允许选择。
当您删除转换时,其中一个选项会消失,因此不再含糊不清。