【发布时间】: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::vectorclass。 -
既然有一个非常有用的
std::vector,为什么还要创建自己的ArrayList类? -
@nneonneo:当然是作业