gpt4 book ai didi

C++ 重载运算符解析

转载 作者:太空狗 更新时间:2023-10-29 23:41:58 24 4
gpt4 key购买 nike

我正在学习 C++ 并使用 C++ Primer。考虑以下练习 14.46:

 class Complex {
Complex(double);
// ...
};

class LongDouble {

friend LongDouble operator+(LongDouble&, int); // (1)

public:
LongDouble(int);

operator double();

LongDouble operator+(const Complex &); // (2)
// ...
};

LongDouble operator+(const LongDouble &, double); // (3)

LongDouble ld(16.08);
double res = ld + 15.05; // which operator+ ?

当我使用 gcc 4.5 编译上述程序时,我得到

14_46.cpp:60:21: error: ambiguous overload for ‘operator+’ in ‘ld + 1.5050000000000000710542735760100185871124267578125e+1’
14_46.cpp:60:21: note: candidates are: operator+(double, double) <built-in>
14_46.cpp:35:5: note: LongDouble LongDouble::operator+(const Complex&)
14_46.cpp:45:1: note: LongDouble operator+(const LongDouble&, double)
14_46.cpp:17:5: note: LongDouble operator+(LongDouble&, int)

为什么 (3) 没有被选中?不是完全匹配吗?

但是,我注意到在 (3) 中删除参数的 const-ness 完全匹配,即,

LongDouble operator+(LongDouble &, double);  // (4)

使用 (4) 没有歧义。我在这里遗漏了什么吗?

最佳答案

您有以下竞争的用户定义函数(候选)

operator+(LongDouble&, int); // friend
operator+(LongDouble&, Complex const&); // member
operator+(LongDouble const&, double); // global

您正在使用参数调用它:

(LongDouble&, double)

对于第一个参数,前两个候选人比最后一个好。对于第二个参数,最后一个候选人比前两个候选人更好。没有候选人在所有论点上至少与所有其他人一样匹配,并且在某些论点上匹配得更好。

对于这种情况,您无法找出明显的赢家。这就是我喜欢称之为“十字交叉”的东西。

在用户定义的候选项中也有内置的候选项。

operator+(double, double);
operator+(int, double);
...

在所有内置候选中,operator+(double, double) 最匹配。但这将需要为第一个参数进行用户定义的转换,这比第一个参数的所有其他三个用户定义的运算符都差,因此它也无法获胜。

关于C++ 重载运算符解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6736467/

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