我将数组的大小声明为 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;
}