我正在编写一个程序来添加两个多项式。我收录了一个重载的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=
时,为什么会出现此错误?
答案 0 :(得分:1)
poly::operator=
的参数是引用,poly::operator+
返回 temp 对象。您不能对temp对象进行非const引用。
让operator=
参加const
参考:
//---------------vvvvv
poly& operator=( const poly &obj){