포인터 그룹 클래스 (연습, 정확하지 않음)

2813 단어
#ifndef STD_PTR_ARRAY_H_
#define STD_PTR_ARRAY_H_

class StdPtrArray {
public:
	StdPtrArray();
	StdPtrArray(int _allocated_count = 0);
	~StdPtrArray();
	void Add(void *_data);
	void *GetIndex(int _index) const;
	void **GetData() const;
	void Remove(int _index);
	bool IsEmpty() const;
private:
	int element_count;
	int allocated_count;
	void **p_value;
};

#endif // STD_PTR_ARRAY_H
/*
	StdPtrArray Class

	YangJie 2011-03-22 13:43
*/

#include "StdPtrArray.h"
#include <cstdlib>
#include <cstring>

StdPtrArray::StdPtrArray() :
	element_count(0), allocated_count(0),
	p_value(NULL)
{}

StdPtrArray::StdPtrArray(int _allocated_count /*=0*/) :
	element_count(0), allocated_count(_allocated_count),
	p_value(NULL)
{
	if (allocated_count == 0)
		allocated_count = 13;
	p_value = (void **)malloc(sizeof(void *) * allocated_count);
	memset(p_value, 0, sizeof(void *) * allocated_count);
}

StdPtrArray::~StdPtrArray()
{
	delete [] p_value;
}

void StdPtrArray::Add(void *_data)
{
	if ((element_count + 1) >= allocated_count) {
		allocated_count *= 2;
		void **p_tmp = (void **)malloc(sizeof(void*) * allocated_count);
		memset(p_tmp, 0, sizeof(void *) * allocated_count);
		memcpy(p_tmp, p_value, sizeof(void *) * (element_count - 1));
		delete [] p_value;
		p_value = p_tmp;
		p_tmp = NULL;
	}
	p_value[element_count] = _data;
	element_count ++;
}

void *StdPtrArray::GetIndex(int _index) const
{
	if (_index > element_count || _index <= 0)
		return NULL;
	return p_value[_index - 1];
}

void **StdPtrArray::GetData() const
{
	return p_value;
}

void StdPtrArray::Remove(int _index)
{
	if ((_index > element_count) || (_index <= 0))
		return ;
	int i = 0;
	for (i = _index - 1; i < element_count - 1; i ++) {
		p_value[i] = p_value[i + 1];
	}
	p_value[i] = 0;
	element_count --;
}

bool StdPtrArray::IsEmpty() const
{
	return (element_count == 0);
}
#include <iostream>
#include "StdPtrArray.h"
using namespace std;

int main(int argc, char *argv[])
{
	StdPtrArray p_arr(13);
	int a = 0;
	int b = 23;
	int c = 33;
	int d = 35;
	char *p1 = "sdrfwewer";

	p_arr.Add((void *)a);
	p_arr.Add((void *)b);
	p_arr.Add((void *)c);
	p_arr.Add((void *)d);
	p_arr.Add(p1);
	
	int p = (int)p_arr.GetIndex(3);
	cout<<p<<endl;

	cout<<(int)p_arr.GetData()[2]<<endl;

	p_arr.Remove(1);
	cout<<(int)p_arr.GetData()[0]<<endl;

	cout<<(char *)p_arr.GetData()[3]<<endl;
	return 0;
}
main.exe:main.obj StdPtrArray.obj
	g++ -o main.exe main.obj StdPtrArray.obj
main.obj:main.cpp StdPtrArray.h
	g++ -c main.cpp -o main.obj
StdPtrArray.obj:StdPtrArray.cpp StdPtrArray.h
	g++ -c StdPtrArray.cpp -o StdPtrArray.obj
clean:
	del *obj *exe

좋은 웹페이지 즐겨찾기