gpt4 book ai didi

c++ - 重载 operator* 与 operator double() 不明确

转载 作者:行者123 更新时间:2023-11-30 05:06:50 25 4
gpt4 key购买 nike

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;

当我删除“operator double()”时,“operator *”会起作用,但是是否可以选择立即将这些操作符提供给运算符(operator)?

代码:

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;
}

最佳答案

xxx * 3 中,编译器可以将 3 转换为 float 并使用 operator*(float xy) 或使用 operator double()xxx 转换为 double,然后使用内置乘法。

规则说这个是有歧义的,所以不能选任何一个。

当您删除转换时,其中一个选项会消失,因此它不再模糊。

关于c++ - 重载 operator* 与 operator double() 不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47738753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com