簡體   English   中英

重載運算符=錯誤

[英]OVERLOADING OPERATORS = error

我正在嘗試使用重載概念將3個對象c1c2c3等同。 但這給我一個錯誤

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

它背后的原因是什么,我該如何糾正它?

#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;
} 

因此,此重載運算符將被調用兩次。首先是c2 = c1,然后是c3 = c2,但是編譯器如何將其與重載運算符定義進行比較?

為了鏈接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解析為c1 = (c2 = c3) 如果operator =不返回引用,則c2 = c3是右值,並且不能綁定到c1.operator =的引用參數c1.operator = (如果該參數是對const的引用,則可以綁定到rvalue,但是並不意味着您不應該返回參考)。

還要注意,通過const引用獲取參數是有意義的,因為您不想更改您分配的參數。

還要記住三個規則 ,也就是說,如果您確實需要執行以下任一操作:

  • 重載operator =

  • 明確提供副本構造函數

  • 明確提供一個析構函數

那么您可能也想做另外兩個。 在您的特定情況下,您似乎根本不需要重載operator =

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM