c++ - 如何更正此程序中的重载赋值?

标签 c++ pointers

大家好:我正在努力将一个类对象的cof分配给另一个类对象。但是,为什么我的重载(=)只能赋值前两个cof!(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,编码会更容易。您可以降低大小(使用 vector 的大小)并复制 vector 。

此外,调用与成员 (size) 不同的 getter (getvalue()) 很容易引起混淆。

关于c++ - 如何更正此程序中的重载赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23033924/

相关文章:

c++ - set object = null 在 C++ 中的替代方法是什么,比如 C#

c++ - Qt例子: no mutex lock when reading,为什么?

c++ - 为什么显式位移运算会产生更大的 .s 文件?

c++ - 什么时候为类成员释放使用 alloca 分配的内存?

将对象传递给它时方法签名之间的 C++ 区别

C++引用类函数错误: identifier is undefined

c++ - 是否可以交换结构数组(线性时间)?

c++ - 将 Vector * 转换为 char *

c - C语言给字符串加一个整数,如何理解结果?

pointers - golang 中的 slice 杂耍