![](/img/trans.png)
[英]Assignment overloading: why does using the same object cause problems in the program?
[英]How to correct the overloading assignment in this program?
大家好:我正在努力將一個類對象的cof分配給另一類對象。 但是,為什么我的重載(=)只能分配前兩個cofs!(cof是指向int的指針)
我是新來的,我不確定如何在此處輸入mu代碼。 我希望有一個人可以幫助我! 謝謝! 這是我的代碼:
#include <iostream>
using namespace std;
class polynomial
{ private :
int* cof;
int size;
public :
polynomial();
polynomial(int );
polynomial(const polynomial& a);
~polynomial();
int getvalue() const;
void operator =(const polynomial& a);
void output(const polynomial& p);
};
int main()
{ int m;
cout<<"how many numbers in p1 :"<<endl;
cin>>m;
polynomial p1(m);
cout<<"how many numbers in p2"<<endl;
cin>>m;
polynomial p2(m);
cout<<"the p1's cof"<<endl;
p1.output(p1);
cout<<"the p2's cof"<<endl;
p2.output(p2);
polynomial t;
t=p1;
cout<<" the t's cof:"<<endl;
t.output(t);
t=p2;
cout<<"the t's cof:"<<endl;
t.output(t);
return 0;
}
polynomial::~polynomial()
{ delete [] cof;}
polynomial:: polynomial():size(1)
{ cof= new int[size];
cof[0]=0;
}
polynomial::polynomial(int a): size(a)
{ cof= new int[size+1];
cout<<"please enter the numbers:"<<endl;
for(int i=0;i<size+1;i++)
cin>>cof[i];
}
polynomial::polynomial(const polynomial& a)
{ cof= new int[a.size+1];
for(int i=0;i<=a.size;i++)
{ cof[i]=a.cof[i];}
}
int polynomial::getvalue() const
{ return size;}
void polynomial::output(const polynomial& p)
{ for(int i=0;i<=p.size;i++)
{ cout<<p.cof[i]<<" ";}
cout<<endl;
}
void polynomial::operator =(const polynomial& a)
{ if (cof!=NULL)
delete [] cof;
int x=a.getvalue();
cof= new int[x+1];
for(int i=0;i<=x;i++)
{ cof[i]=a.cof[i];}
}
您只是忘了復制尺寸。
void polynomial::operator =(const polynomial& a) {
if (cof!=NULL) delete [] cof;
size = a.getvalue(); // <<< !!!
cof = new int[size+1];
for(int i = 0; i < size + 1; i++){
cof[i]=a.cof[i];}
}
}
如果刪除過時的C樣式數組並使用std :: vector,則編碼會更容易。 您可以刪除大小(使用向量的大小),然后復制向量。
另外,調用不同於成員(大小)的getter(getvalue())容易引起混亂。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.