qiaoxu123
10/1/2018 - 12:36 PM

C++ 数组类

利用C++特性创建一个安全可靠的数组类型

#include "IntArray.h"	

IntArray::IntArray(int len) {
	m_length = len;
}

bool IntArray::construct() {
	bool ret = true;
	m_pointer = new int[m_length];
	if (m_pointer) {
		for (int i = 0; i < m_length; ++i) {
			m_pointer[i] = 0;
		}
	}
	else {
		ret = false;
	}
	return ret;
}

IntArray* IntArray::NewInstance(int length) {	//二阶构造
	IntArray* ret = new IntArray(length);
	if (!(ret && ret->construct())) {
		delete ret;
		ret = 0;
	}
	return ret;
}

int IntArray::length() {		//返回函数长度
	return m_length;
}

bool IntArray::get(int index, int& value) {			//函数取值,使用引用对数值进行修改
	bool ret = (0 <= index) && (index < length());
	if (ret) {
		value = m_pointer[index];
	}
	return ret;
}

int& IntArray::operator[](int index) {	//重构[]运算符
	return m_pointer[index];
}

IntArray& IntArray::self() {
	return *this;
}

IntArray::~IntArray() {					//析构函数,删除数组
	delete[] m_pointer;
}




#include <iostream>
#include <string>
#include "IntArray.h"

using namespace std;

int main() {
	IntArray* a = IntArray::NewInstance(5);

	if (a != NULL) {
		IntArray& array = a->self();
		cout << "array.length() = " << array.length() << endl;
		array[0] = 1;
		for (int i = 0; i < array.length(); ++i) {
			cout << array[i] << endl;
		}
	}
	delete a;

	getchar();
	return 0;
}
#ifndef _INTARRAY_H_
#define _INTARRAY_H_

class IntArray {
private:
	int m_length;
	int* m_pointer;

	IntArray(int len);
	IntArray(const IntArray& obj);
	bool construct();
public:
	static IntArray * NewInstance(int length);
	int length();
	bool get(int index, int& value);
	bool set(int index, int valaue);
	int &operator [](int index);
	IntArray& self();
	~IntArray();
};



#endif // !_INTARRAY_H_