一维数组的实现(Array, C++版)

类别:编程语言 点击:0 评论:0 推荐:

#ifndef __ARRAY_H__
#define __ARRAY_H__ 1

#include <iostream.h>

extern "C" { void exit(int); }

template <class T>
class Array {
private:
    int FSize; //数组的大小
    T   *alist; //指向数组的第一个元素的指针
    //为数组申请内存空间
    void Allocate() {
        alist = new T[FSize];
        if (!alist) {
            cerr << "Memory Allocation Error!" << endl;
            exit(1);
        }
    }
public:
    //构造函数
    Array(int sz = 50) {
        if (sz <= 0) sz = 1;
        FSize = sz;
        Allocate();
    }
    //复制构造函数:在声明数组时复制动态数组x
    Array(const Array<T> &x) {
        FSize = x.FSize;
        Allocate();
        for (int i=0; i < FSize; i++)
            alist[i] = x.alist[i];
    }
    //析构函数
    ~Array() {
        if (FSize > 0) {
            delete [] alist;
            FSize = 0;
        }
    }
    //返回数组大小
    int ListSize() { return FSize; }
    //赋值运算符的重载
    Array<T> & operator = (const Array<T> & x) {
        if (FSize > 0) delete [] alist;
        FSize = x.FSize;
        Allocate();
        for (int i=0; i < FSize; i++)
            alist[i] = x.alist[i];
        return *this;
    }
    //数组下标运算符[]的重载
    T& operator[](int i) {
        if (i < 0 || i > FSize) {
            cerr << "Invalid Index!" << endl;
            exit(1);
        }
        return alist[i];
    }
    //类型转换
    operator T*() const {
        return alist;
    }
    //修改数组大小
    void Resize(int newSize) {
        if (newSize <= 0) {
            cerr << "Invalid Array Size." << endl;
            return;
        }
        if (newSize != FSize) {
            T   *newList = new T[newSize];
            if (!newList) {
                cerr << "Memory Allocation Error !" << endl;
                exit(1);
            }
            int n = (newSize <= FSize ? newSize : FSize);
            //复制数组
            for (int i=0; i < n; i++)
                newList[i] = alist[i];
            delete [] alist; //释放原数组所占空间
            alist = newList;
            FSize = newSize;
        }
    }
};
#endif /* !__ARRAY_H__ */
//以上为class Array的定义,请存放至array.h文件中

//以下为测试程序
#include <iostream.h>
#include <iomanip.h>
#include "array.h"

void main() {
    Array<int>  A(10), B(A), C; //构造函数的测试
    int N, i, count=0;
    cout << "List Size : " << A.ListSize() << endl;
    A[5] = 30;
    B[5] = 50;
    cout << "A[5] = " << A[5] << endl;
    cout << "B[5] = " << B[5] << endl;
    A = B; //赋值运算符的测试
    cout << "A[5] = " << A[5] << endl;
    cout << "B[5] = " << B[5] << endl;
    cout << " N = ? ";
    cin >> N;
    for (i = 5; i <= N; i++) {
        if (count == A.ListSize())
            A.Resize(count + 10); //Resize()的测试
        if (i%5==0 || i%7==0)
            A[count++] = i;
    }
    //输出数组
    for (i=0; i < count;) {
        cout << setw(5) << A[i++];
        if (i%5 == 0) cout << endl;
    }
    if (i%5) cout << endl;
    cout << ((int *)A)[5] << endl;
}

本文地址:http://com.8s8s.com/it/it25565.htm