0

我将数组的大小声明为 2,并尝试在第三个数组位置插入。当位置> size + 1(将元素分配到数组时使用pos-1)时,插入函数应该抛出-1,但抛出并没有停止对第三个数组位置的分配,所以我遇到了分段错误。

template <class T, int N>
class person : public people<T>
{
    private:
    T a[N];
    int size;
    public:
    person();
    virtual void insert(int pos, T info);
    virtual T show(int pos);
};
template<class T, int N>
person<T,N>::person(){
    size = 0;
}
template <class T, int N>
void person<T,N>::insert(int pos, T info){
    if (pos <= 0 || pos > size+1)
        throw -1;
    a[pos-1] = info;
    ++size;
}
template <class T, int N>
T person<T,N>::show(int pos){
    if ( pos <= 0 || pos > size+1 )
            throw -1;
      return a[pos-1];
}

void putin( people<name>*& aPerson ) {//passing aPerson itself

    string first("Julia"), last("Robert");
    name temp(first, last);
    string ft("Delilah"), lt("McLuvin");
    name temp2(ft, lt);
    string fst("oooh lala"), lst("broomdat");
    name temp3(fst, lst);

    try{
    aPerson-> insert(1,temp);
    aPerson-> insert(2,temp2);
    aPerson-> insert(3,temp3);
    }
    catch(...){ cout<< "error\n";}

}


int main(){
    people<name>* aPerson = new person<name, 2>();
    putin(aPerson);
    try{
    cout << aPerson->show(1);
    cout << aPerson->show(2);
    cout << aPerson->show(3);
    }
    catch(...){ cout<< "error\n";}
    return 0;
}
4

2 回答 2

3

每次插入某些东西时,都会检查大小变量,然后再增加它。当你达到 size == N 时,什么也没有发生。您只需超出数组范围,就需要考虑大小即将变得大于数组的情况。

于 2013-11-10T04:00:48.497 回答
0

你在使用 STL 吗?如果是,最好尝试使用vector<T>::at安全方法,该方法将为您进行所有必要的检查,并std::out_of_range在超出其范围时抛出异常。

于 2013-11-10T05:15:17.963 回答