东大树莓数据结构S2Array代码

代码从课件上扒下来的,修改增加了部分代码,学习备考使用。

Array.cpp
#include 
using namespace std;

template
class Array {
	T* elements;
	int ArraySize;
	void getArray();
public:
	Array(int Size = DefaultSize);
	Array(const Array& x);
	~Array() { delete[] elements; }
	Array& operator=(const Array& A);
	T& operator[](int i);
	T* operator*() const { return elements; }
	int Length() const { return ArraySize; }
	void ReSize(int sz);
	void DisplayElements();
};

template
void Array::getArray() {
	elements = new T[ArraySize];
	if (elements == 0) {
		ArraySize = 0;
		cerr << "Memory Allocation Error" << endl;
		return;
	}
}

template
Array::Array(int sz) {
	if (sz <= 0) {
		ArraySize = 0;
		cerr << "非法数组大小" << endl;
		return;
	}
	ArraySize = sz;
	getArray();
}

template
Array::Array(const Array& x) {
	int n = ArraySize = x.ArraySize;
	elements = new T[n];
	if (elements == 0) {
		ArraySize = 0;
		cerr << "存储分配错" << endl;
		return;
	}
	T* srcptr = x.elements;
	T* destptr = elements;
	while (n--) { *destptr++ = *srcptr++; }
}

template
Array& Array::operator=(const Array& A) {
	if (this == &A) {
		return *this;
	}
	delete[] elements;
	ArraySize = A.ArraySize;
	elements = new T[ArraySize];
	for (int i = 0; i < ArraySize; i++) {
		elements[i] = A.elements[i];
	}
	return *this;
}

template
T& Array::operator[](int i) {
	if (i<0 || i>ArraySize - 1) {
		cerr << "数组下标越界" << endl;
		static T default_value = T();
		return default_value;
	}
	return elements[i];
}

template
void Array::ReSize(int sz) {
	if (sz >= 0 && sz != ArraySize) {
		T* newarray = new T[sz];
		if (newarray == 0) {
			cerr << "存储分配错" << endl;
			return;
		}
		int n = (sz <= ArraySize) ? sz : ArraySize;
		T* srcptr = elements;
		T* destptr = newarray;
		while (n--) { *destptr++ = *srcptr++; }
		delete[] elements;
		elements = newarray;
		ArraySize = sz;
	}
}

template
void Array::DisplayElements() {
	for (int i = 0; i < ArraySize; i++) {
		cout << elements[i] << " ";
	}
	cout << endl;
}
test.cpp
#include "Array.cpp"

int main(){
    //cout << "test" << endl;
    Array arr(5);
    for (int i = 0; i < 5; i++) {
        arr[i] = i + 1;
    }
    cout << arr.Length() << endl;
    arr.DisplayElements();
    arr.ReSize(3);
    arr.DisplayElements();
    arr.ReSize(6);
    arr.DisplayElements();

    Array brr(6);
    Array crr(6);
    for (int i = 0; i < 6; i++) {
        brr[i] = 'a' + i;
    }
    brr.DisplayElements();
    crr = brr;
    crr.DisplayElements();
    cout << crr.Length() << endl;
    return 0;
}

你可能感兴趣的:(数据结构,c++)