简体   繁体   English

重载运算符=错误

[英]OVERLOADING OPERATORS = error

I am trying to use overloading concept to equate 3 objects c1 , c2 , c3 . 我正在尝试使用重载概念将3个对象c1c2c3等同。 But it is giving me an error 但这给我一个错误

error: no match for 'operator=' in 'c3 = c2. circle::operator=(((circle&)(& c1)))'

What's the reason behind it how do I rectify it?? 它背后的原因是什么,我该如何纠正它?

#include<iostream>
using namespace std;

class circle
{
  private:
    int radius;
    float x,y;
  public:
    circle()
    {}
    circle(int rr,float xx,float yy)
    {
      radius=rr;
      x=xx;
      y=yy;
    }
    circle& operator=(const circle& c)
    {
     cout<<endl<<"assignment operator invoked";  
     radius=c.radius;
     x=c.x;
     y=c.y;
     return *this;
     }
    void showdata()
    {
      cout<<endl<<"\n radius="<<radius;
      cout<<endl<<"x coordinate="<<x;
      cout<<endl<<"y coordinate="<<y<<endl;
    }
};
int main()
{
  circle c1 (10,2.5,2.5);
  circle c2,c3;
  c3=c2=c1;
  c1.showdata();
  c2.showdata();
  c3.showdata();
  return 0;
} 

so this overloaded operator will be called two times.. First for c2=c1 and then for c3=c2 but how will compiler compare it with overloaded operator definition?? 因此,此重载运算符将被调用两次。首先是c2 = c1,然后是c3 = c2,但是编译器如何将其与重载运算符定义进行比较?

In order to chain operator= calls, you must make sure that it returns a reference 为了链接operator=调用,必须确保它返回引用

circle& operator=(const circle& c)
{
   cout<<endl<<"assignment operator invoked";  
   radius=c.radius;
   x=c.x;
   y=c.y;
   return *this;
}

c1=c2=c3 is parsed as c1 = (c2 = c3) . c1=c2=c3解析为c1 = (c2 = c3) If operator = doesn't return a reference, c2 = c3 is an rvalue, and it cannot bind to the reference argument of c1.operator = (In case if the argument is a reference to const, it can bind to rvalues, but that doesn't mean you shouldn't return a reference). 如果operator =不返回引用,则c2 = c3是右值,并且不能绑定到c1.operator =的引用参数c1.operator = (如果该参数是对const的引用,则可以绑定到rvalue,但是并不意味着您不应该返回参考)。

Also note that it makes sense to take the parameter by const reference, because you don't want to change the argument that you assign. 还要注意,通过const引用获取参数是有意义的,因为您不想更改您分配的参数。

Also remember the rule of three , that is, if you really need to do any of the following: 还要记住三个规则 ,也就是说,如果您确实需要执行以下任一操作:

  • overload operator = 重载operator =

  • explicitly provide a copy constructor 明确提供副本构造函数

  • explicitly provide a destructor 明确提供一个析构函数

then you probably want to do the other two too. 那么您可能也想做另外两个。 In your particular case, you don't seem to need to overload operator = at all. 在您的特定情况下,您似乎根本不需要重载operator =

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM