【提示】编写void put(int n)函数时,注意考虑数组满的情况。如果数组已满,则没有空间存储n,此时需动态申请新的内存空间,其大小应比原数组大小大1,并将原数组元素备份到新数组,新数组的最后一个元素存放n,当然不要忘记释放为原数组动态分配的内存空间。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 #include <iostream> using namespace std; class ListArray { private : int size; //整型数组的大小,表示可放元素的个数 int elem; //整型数组当前的元素个数,初始应为0,当elem等于size时,数组满 int *p; //指向整型数组,动态分配内存空间 public : ListArray( int s=100); //用s初始化整型数组的大小 void put( int n); //将n加入整型数组,elem自增1 void print(); //输出整型数组所有元素 ~ListArray(); }; //start ListArray::ListArray( int s) { size = s; elem = 0; if (s) p = new int [s]; else p = NULL; } void ListArray::put( int n) { int *t; if (p == NULL) { p = new int [1]; p[0] = n; elem = size = 1; } else { if (elem == size) { size ++; t = new int [size]; for ( int i = 0; i < elem; i ++) t[i] = p[i]; t[elem ++] = n; delete [] p; p = t; } else p[elem ++] = n; } } void ListArray::print() { for ( int i = 0; i < elem; i ++) cout << p[i] << ' ' ; cout << endl; } ListArray::~ListArray() { if (p) delete [] p; } //end //test code int main() { ListArray a(2); a.put(1); a.put(2); a.print(); a.put(3); a.print(); a.put(5); a.print(); return 0; }