【问题标题】:Creating an Array List of Person Objects in C++在 C++ 中创建人员对象的数组列表
【发布时间】:2013-01-28 14:24:53
【问题描述】:

我正在尝试在 C++ 中为我拥有的项目创建一个 Person 对象的数组列表。我是 C++ 编程新手,所以我不确定从哪里开始。程序成功构建,但在将人对象插入索引 0 的行中出现奇怪的线程错误。有人可以指出如何将对象插入数组列表的正确方向吗?谢谢!

这是我的 Person 类:

#include <iostream>
using namespace std;

class Person
{
public:
    string fName;
    string lName;
    string hometown;
    string month;
    int day;

    Person();
    Person(string f, string l, string h, string m, int d);
    void print();
    int compareName(Person p);

};

Person::Person(string f, string l, string h, string m, int d) {
    fName = f;
    lName = l;
    hometown = h;
    month = m;
    day = d;
}

void Person::print() {
    std::cout << "Name: " << lName << ", " << fName <<"\n";
    std::cout << "Hometown: " << hometown <<"\n";
    std::cout << "Birthday: " << month << " " << day <<"\n";
}

ArrayList.h

#ifndef __Project2__ArrayList__
#define __Project2__ArrayList__

#include <iostream>
#include "Person.h"


class ArrayList {
public:
    ArrayList();

    bool empty() const {return listSize ==0;}
    int size() const {return listSize;}
    int capacity() const {return arrayLength;}
    void insert(int index, Person *p); //insertion sort
    void output();


protected:
    Person* per;
    int arrayLength;
    int listSize;

};
#endif

ArrayList.cpp:

#include "ArrayList.h"
#include <iostream>
using namespace std;

ArrayList::ArrayList()
{
    arrayLength = 10;
    listSize = 0;
}

void ArrayList::insert(int index, Person *p)
{
    per[index] = *p;
    listSize++;
}


void ArrayList::output()
{
    for(int i=0; i<listSize; i++)
    {
        per[i].print();
    }
}

【问题讨论】:

  • 指针不是数组!此外,您的包含保护标识符可能会更好:stackoverflow.com/questions/228783/…
  • 你从未分配过内存。除非您是出于学习目的而这样做,否则请查看std::vector class。
  • 既然有一个非常有用的std::vector,为什么还要创建自己的ArrayList 类?
  • @nneonneo:当然是作业

标签: c++ arrays list arraylist


【解决方案1】:

您的指针未初始化,它没有引用有效的内存位置。如果您打算以这种方式实现数据结构,则需要对其进行初始化,然后检查是否需要在插入时重新分配。

ArrayList::ArrayList(size_t capacity)
{
    _capacity = capacity;
    _list_size = 0;
    // initialize your backing store
    _per = new Person[_capacity];
}

您还需要正确处理释放、分配、复制等。

【讨论】:

  • 那么通过添加 per = new Person[capacity] 行,数组会被初始化吗?另外,构造函数参数中的“size_t”类型是什么?抱歉,我对 c++ 很陌生,指向对象的指针的想法仍然让我感到困惑。我发现了如何创建原始数据类型的数组列表,但使用对象创建一个数组列表让我感到困惑。
  • operator new [] 返回一个指向内存块的指针,该内存块包含capacity 个默认初始化对象(在本例中为Person 对象)。 size_t 可以在文档中找到:en.cppreference.com/w/cpp/types/size_t
猜你喜欢
  • 1970-01-01
  • 2014-10-13
  • 1970-01-01
  • 2012-08-04
  • 1970-01-01
  • 2021-10-21
  • 1970-01-01
  • 1970-01-01
  • 2021-11-05
相关资源
最近更新 更多