gpt4 book ai didi

c++ - ClassType 转换 - 运算符 + 不明确

转载 作者:搜寻专家 更新时间:2023-10-31 00:20:54 25 4
gpt4 key购买 nike

在下文中,我希望将 obj 转换为 int 但为什么在下文中它会返回 operator + ambiguous?

class MyClass
{
public:
MyClass(int X = 0, double Y = 0):x(X), y(Y){}

operator int() const { return x; }
operator double() const { return y; }

private:
int x;
double y;
};

int main()
{
MyClass obj(10, 20);

int x = obj + 5; //obj converted to int
}

最佳答案

因为这两种转换是等价的,所以它是不明确的。请记住,C++ 语言直接为 doubleint 的参数定义了 +,不涉及标准转换。

所以这两个函数都不比另一个好:

  • double operator+ (double, int) -- 需要一个用户定义的转换,不需要标准转换
  • int operator+ (int, int) -- 需要一个用户定义的转换,不需要标准转换

如果你想完成这项工作,你需要自己提供所有常用的算术运算符,而不是依赖隐式转换运算符。

  • double operator+ (const MyClass&, int) -- 需要一个标准转换
  • int operator+ (const MyClass&, double) -- 不需要转换

现在 obj + 5 将有一个明确的最佳匹配。


C++0x 草案 n3245 在 [over.built] 部分说

  • In this subclause, the term promoted integral type is used to refer to those integral types which are preserved by integral promotion (including e.g. int and long but excluding e.g. char). Similarly, the term promoted arithmetic type refers to floating types plus promoted integral types.

For every pair of promoted arithmetic types L and R, there exist candidate operator functions of the form

LR operator*(L,  R);
LR operator/(L, R);
LR operator+(L, R);
LR operator-(L, R);
bool operator<(L, R);
bool operator>(L, R);
bool operator<=(L, R);
bool operator>=(L, R);
bool operator==(L, R);
bool operator!=(L, R);

where LR is the result of the usual arithmetic conversions between types L and R.

关于c++ - ClassType 转换 - 运算符 + 不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5366080/

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