1

私が持っているプロジェクトのために 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();
    }
}
4

1 に答える 1

1

ポインタが初期化されていないため、有効なメモリ位置を参照していません。この方法でデータ構造を実装する場合は、初期化してから、挿入時に再割り当てが必要かどうかを確認する必要があります。

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

また、割り当て解除、割り当て、コピーなどを適切に処理する必要があります。

于 2013-02-13T05:16:49.987 に答える