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=

4

1 回答 1

1

poly::operator=的参数是引用并poly::operator+返回一个临时对象。您不能对临时对象进行非常量引用。

做你的operator=参考const

//---------------vvvvv
poly& operator=( const poly &obj){
于 2012-10-08T19:10:20.253 回答