2012-10-08 14 views
0

我在編寫一個程序來添加兩個多項式。我已經包括一個超載operator=operator+。這裏的代碼:運算符重載加兩個多項式誤差

#include<iostream> 
using namespace std; 
#define MAX 30 


class poly{ 
public: 
    int arr[MAX][2]; 
    int count; 
    poly():count(0){} 
    poly(int x){ 
     cout<<"Enter the number of terms:\t"; 
     cin>>count; 
     cout<<"Enter the terms:\n"; 
     for(int i=0; i<count; i++){ 
      for(int j=0; j<2; j++) 
       cin>>arr[i][j]; 
     } 
    } 
    void swap(int a[2], int b[2]){ 
     int temp1 = a[1], temp2 = a[0]; 
     a[1] = b[1]; a[0] = b[0]; 
     b[0] = temp1; b[1] = temp2; 
    } 

    void sorting(){ 
     for(int i=0; i<count-1; i++){ 
      for(int j=0; j<count-i-1; j++){ 
       if(arr[j][1] > arr[j+1][1]) 
        swap(arr[j], arr[j+1]); 
      } 
     } 
    } 

    poly& operator=(poly &obj){ 
     count = obj.count; 
     for(int i=0; i<count; i++){ 
      arr[i][0] = obj.arr[i][0]; 
      arr[i][1] = obj.arr[i][1]; 
     } 
     return *this; 
    } 

    poly operator+(poly &obj){ 
     poly obj3; 
     int i = 0, j = 0, k=0; 
     while(i<count && j<obj.count){ 
      if(arr[i][1] == obj.arr[j][1]){ 
       obj3.arr[k][1] = arr[i][1]; 
       obj3.arr[k][0] = arr[i][0] + obj.arr[j][1]; 
       i++; j++;k++; 
      } 
      else if(arr[i][1] < arr[j][1]){ 
       obj3.arr[k][1] = arr[i][1]; 
       obj3.arr[k][0] = arr[i][0]; 
       i++;k++; 
      } 
      else{ 
       obj3.arr[k][1] = obj.arr[j][1]; 
       obj3.arr[k][0] = obj.arr[j][0]; 
       j++;k++; 
      } 
     } 
     while(i<count){ 
      obj3.arr[k][1] = arr[i][1]; 
      obj3.arr[k][0] = arr[i][0]; 
      i++;k++; 
     } 
     while(j<obj.count){ 
      obj3.arr[k][1] = obj.arr[j][1]; 
      obj3.arr[k][0] = obj.arr[j][0]; 
      j++;k++; 
     } 
     return obj3; 
    } 

    void display(){ 
     cout<<"The expression is:\t"; 
     cout<<arr[0][0]<<"y"<<arr[0][1]; 
     for(int i=1; i<count; i++) 
      cout<<"+"<<arr[i][0]<<"y"<<arr[i][1]; 
     cout<<endl; 
    } 
}; 

int main(){ 
    poly obj(5), obj1(3), obj3; 
    obj.display(); 
    obj1.display(); 
    obj3 = obj; 
    obj3 = (obj + obj1); 
    obj3.sorting(); 
    obj3.display(); 
    return 0; 
} 

我已經假設多項式按照他們的權力增加順序排列,同時由用戶輸入。但是在編譯時它顯示錯誤:

In function ‘int main()’: 
error: no match for ‘operator=’ in ‘obj3 = obj. poly::operator+(((poly&)(& obj1)))’ 
note: candidates are: poly& poly::operator=(poly&) 

爲什麼會出現這種錯誤發生的時候我已經超負荷operator=

回答

1

poly::operator=的參數是參考和poly::operator+返回一個臨時對象。您不能對臨時對象進行非const引用。

讓您operator=採取const參考:

//---------------vvvvv 
poly& operator=(const poly &obj){