c++ - 进程退出,值为 3221225477

标签 c++ class dynamic-arrays

我创建了一个使用动态数组的程序。它有效,当我使用我的插入函数然后我显示数组的元素时,它显示了我想要的所有内容。问题是在程序结束时它没有返回值 0,而是被阻塞了几秒钟并说“进程退出值 3221225477”。怎么了?

标题:

#ifndef VETTORE_H
#define VETTORE_H
#include "regalo.h"

typedef regalo T;

class vettore {
    friend ostream& operator<<(ostream&,const vettore&);
    friend istream& operator>>(istream&,vettore&);
    private:
        T *v;
        int riemp;
        int max;
    public:
        vettore();
        vettore(const int);
        ~vettore(){delete [] v;};
        bool full(){return riemp==max;};
        bool empty()const;
        bool inserisci(const T&);
        T& operator[](const int index);

};

#endif

cpp文件:

#include "vettore.h"

ostream &operator<<(ostream& out,const vettore & v1){
    for(int i=0;i<v1.riemp;i++){
        out<<v1.v[i];
    }
    return out;
}

istream &operator>>(istream& in,vettore &v1){
    for(int i=0;i<v1.riemp;i++){
        in>>v1.v[i];
    }
return in;
}

vettore::vettore(){
    riemp=0;
    max=10;
    v=new T[max];
}

vettore::vettore(const int n):max(n),riemp(0){
    v=new T[max];
}

bool vettore::empty()const{
if(riemp==0){
return true;
}else return false;
}

bool vettore::inserisci(const T& n){
    if(max==0){
        cout<<"Inserisci il massimo di elementi del vettore: ";
        cin>>max;
    }
    if(!full()){
        v[riemp]=n;
        riemp++;
        return true;
    }else return false;
}

T& vettore::operator[](const int index){
    return v[index];
}

主文件:

#include "vettore.h"

int main(int argc, char** argv) {
    int riempimento;
    vettore vett(1);
    regalo r1("Alex",300,"quadrato");

    vett.inserisci(r1);
    cout<<"Gli elementi del vettore sono: \n";
    for(int i=0;i<riempimento;i++){
        cout<<vett[i]<<endl;
    }
    system("PAUSE");
    return 0;
}

最佳答案

您的代码中存在一些问题:

  1. riempimento 未初始化,因此 main 中的 for 循环将执行未知次数的迭代,可能超过 vector 的大小。最好从 vector 内部公开 riemp 的值并在循环中使用它。
  2. 您需要实现 rule of three ,这还没有给您带来问题,但如果您复制 vettore 对象,将来会造成问题。
  3. 如果 max 为 0,当您调用 inserisci 时提示用户输入 max 值,您不会检查 cin 是否成功并且您不会重新分配 v 使其足够大以包含 max 元素。
  4. 这不是问题,但是 empty 可以简单地实现为:

    bool vettore::empty()const{
      return riemp==0;
    }
    

关于c++ - 进程退出,值为 3221225477,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52353973/

相关文章:

c++ - 无法理解为什么 for-loop 运行 5 次而不是 4 次

C - 在没有 realloc 的情况下为 stdin 动态分配数组

c++ - 删除数组时出现堆损坏错误

javascript - 如何将自己的 <divs> 动态添加到容器中?

javascript - jQuery 从类数组中查找类名值

c++ - C/C++ - 计算函数调用中的参数

c++ - C++ 如何将文件发送到浏览器

c++ - 如何从 C 调用在 MATLAB 中创建并在 C 中编译的函数?

javascript - ES6 类变量替代方案

iphone - 从类方法中将委托(delegate)设置为 "self"