2012-10-08 2 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+임시 개체를 반환합니다. temp 객체에 대한 const가 아닌 참조는 가질 수 없습니다.

을 확인하여 operator=const 참조 걸릴 :

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