簡體   English   中英

當調用operator =方法時,拋出std :: bad_alloc異常C ++

[英]std::bad_alloc exception thrown when operator= method is called C++

我正在用C ++寫我的第一個類,它是一個多項式,在執行時遇到了bad_alloc異常

P=Q; //(P,Q being polynomials)

我想拋出bad_alloc的事實(有時進程以-1073741819狀態終止)與內存已滿的事實無關,而與根本上是我構造類的方式有誤的事實(以及這也是我第一次使用動態內存。 任何幫助深表感謝。

class  Polinom
{
    int grad;
    int * coef;
public:
    Polinom(){ coef=new int; coef[0]=0; grad=0;}
    Polinom(int x, int *c);
    Polinom(int x) {coef=new int[x];}
    Polinom(const Polinom &);
    ~Polinom(){ delete[] coef; }
    Polinom operator=(Polinom);
};

Polinom::Polinom(int x, int * c)
{
    int i;
    coef=new int[x];
    for(i=0;i<x;i++)
    {
        coef[i]=c[i];
    }
}

Polinom::Polinom(const Polinom &Q)
{
    int i;
    grad=Q.grad;
    coef=new int[grad];
    for(i=0;i<grad;i++)
    {
        coef[i]=Q.coef[i];
    }
}

Polinom Polinom::operator=(Polinom Q)
{
    int i;
    delete[] coef;
    grad=Q.grad;
    coef=new int[grad];
    for(i=0;i<grad;i++)
        coef[i]=Q.coef[i];

    cout<<"finally";
    return (*this);
}

int main()
{
    int *v,*w;
    int i,n;

    cin>>n;
    v=new int[n];
    for(i=0;i<n;i++){ cin>>v[i]; }
    Polinom P(n,v);
    delete[] v;

    cin>>n;
    w=new int[n];
    for(i=0;i<n;i++){ cin>>w[i]; }
    Polinom Q(n,w);
    delete[] w;

    P=Q;

    return 0;
}

在您的構造函數中

Polinom::Polinom(int x, int * c)
{
  int i;
  coef=new int[x];
  for(i=0;i<x;i++)
  {
    coef[i]=c[i];
  }
}

您忘記將grad的值更新為x。 這會導致您的=運算符中的Q.grad包含垃圾並失敗。

這是更改的代碼

Polinom::Polinom(int x, int * c)
{
  int i;
  grad = x;
  coef=new int[x];
  for(i=0;i<x;i++)
  {
    coef[i]=c[i];
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM