我正嘗試在C++中爲我有的項目創建一個Person對象的Array列表。我是C++新手,所以我不確定從哪裏開始。該程序的構建成功,但我得到一個奇怪的線程錯誤在我插入一個人對象到索引0的行。有人請指出我如何將對象插入到數組列表的正確方向?謝謝!在C++中創建Person對象的數組列表
這裏是我的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();
}
}
指針不是數組!此外,你的包括後衛標識符可能會更好:http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-ntifntifier – chris 2013-02-13 05:15:10
你從來沒有分配內存。除非你是爲了學習目的而做的,否則看看'std :: vector'類。 – Asha 2013-02-13 05:17:38
爲什麼在有一個非常有用的'std :: vector'時創建自己的'ArrayList'類? – nneonneo 2013-02-13 05:19:04