【问题标题】:c++ overload operator resolutionc++ 重载运算符解析
【发布时间】:2011-07-18 16:57:38
【问题描述】:

我正在学习 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) 没有歧义。我在这里遗漏了什么吗?

【问题讨论】:

    标签: c++ overload-resolution


    【解决方案1】:

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

    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) 匹配得最好。但这需要对第一个参数进行用户定义的转换,这比第一个参数的所有其他三个用户定义的运算符都差,因此它也无法获胜。

    【讨论】:

    • 谢谢。我不知道const 限定符也在解析过程中起作用。
    【解决方案2】:

    解决此问题的首选方法是将const 添加到版本 1:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 2014-05-06
      • 1970-01-01
      • 2016-02-19
      • 1970-01-01
      相关资源
      最近更新 更多