2013-02-13 103 views
1

我正嘗試在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(); 
    } 
} 
+0

指針不是數組!此外,你的包括後衛標識符可能會更好:http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-ntifntifier – chris 2013-02-13 05:15:10

+0

你從來沒有分配內存。除非你是爲了學習目的而做的,否則看看'std :: vector'類。 – Asha 2013-02-13 05:17:38

+0

爲什麼在有一個非常有用的'std :: vector'時創建自己的'ArrayList'類? – nneonneo 2013-02-13 05:19:04

回答

1

你的指針是未初始化的,它並不指向一個有效內存位置。如果你要這樣實現你的數據結構,你需要初始化它,然後檢查在插入時是否需要重新分配。

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

您還需要妥善處理重新分配,分配,複製等

+0

那麼通過添加per = new Person [容量]行數組將被初始化?另外,構造函數參數中的「size_t」是什麼類型?對不起,我對C++非常陌生,指向對象的想法仍然讓我感到困惑。我已經發現如何創建一個基本數據類型的數組列表,但使一個使用對象令我困惑。 – 2013-02-13 21:40:41

+0

'operator new []'返回一個指向一個內存塊的指針,該內存塊包含默認初始化對象(本例中爲Person對象)的容量數目。 'size_t'可以在以下文檔中找到:http://en.cppreference.com/w/cpp/types/size_t – 2013-02-13 22:18:17

+0

明白了!謝謝! – 2013-02-14 03:13:24