【问题标题】:C++ Operator overloaded using friend function. Attempt to add multiple objects failed使用友元函数重载的 C++ 运算符。尝试添加多个对象失败
【发布时间】:2018-11-19 12:11:14
【问题描述】:

为什么编译器在第二种情况下显示“错误”? (我已经给出了完整程序的链接) 为什么我必须使用 const 关键字?

第一种情况:

friend Complex operator + (const Complex &,const Complex &);

Complex c5 = c1+c2+c3+c4; 

第二种情况:

friend Complex operator + ( Complex &, Complex &); 

Complex c5 = c1+c2+c3+c4; 

1st case Full Program - 我得到正确的输出

2nd case Full Program - 错误:'operator+' 不匹配

【问题讨论】:

    标签: c++ operator-overloading overloading


    【解决方案1】:

    Complex& 不会绑定到临时的,Complex const& 会。

    每个+ 返回一个临时的。

    作为一般规则,您希望:

    friend Complex operator + (Complex,const Complex &);
    

    但是这里有两个const& 就可以了。

    【讨论】:

      【解决方案2】:

      临时对象不绑定到非常量引用。当你写这篇文章时

      auto c3 = c2 + c1 + c0; 
      

      然后首先计算c1+c0,并将结果传递给c2.operator+()。当操作员被声明为采用Complex& 时,您不能传递临时值,当它采用const Complex& 时,您可以。在 90% 的情况下,在需要非常量引用时传递临时值是逻辑错误,因此是禁止的。

      【讨论】:

        【解决方案3】:

        表达式 c1+c2+c3+c4 被解析和评估为 if

        Complex c5 = operator+(c1, operator+(c2, operator+(c3, c4)));
        

        operator+(c3, c4) 构建并返回一个临时的Complex 对象:一个右值。

        C++ 禁止将右值绑定到非 const 左值引用

        operator+(Complex&, Complex&) 采用非常量左值引用。因此出现错误消息。

        另一方面,operator+(Complex const&, Complex const&) 引用 const 左值。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-03-19
          • 2017-07-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-09-09
          • 1970-01-01
          相关资源
          最近更新 更多