模板类 通用数组的实现

实现自定义数组, 重载[] , << , = 运算符 , 并且数组可以使用自定义类

头文件

#ifndef __MYARRAY_H__
#define __MYARRAY_H__

#include 
using namespace std;

template 
class MyArray
{
	friend ostream & operator<< ( ostream &out, const MyArray &obj);
public:
	MyArray ();
	MyArray (int len);
	MyArray (const MyArray &obj);
	~MyArray();
public:
	T & operator[](int index);
	MyArray & operator=(const MyArray &obj);
public:
	int getlen();
private:
	T *m_p ;
	int len;
};

template 
MyArray::MyArray()
{
	m_p = NULL;
}

template 
MyArray::MyArray (int len)
{
	this->len = len;
	m_p = new T[len];
}

template 
MyArray::MyArray (const MyArray &obj)
{
	len = obj.len;
	m_p = new T[len];
	for(int i = 0; i
MyArray::~MyArray()
{
	if (m_p != NULL)
		delete [] m_p;
	len = 0;
}

template 
T & MyArray::operator[](int index)
{
	return m_p[index];
}

template 
MyArray & MyArray::operator=(const MyArray &obj)
{
	if(this == &obj)
		return *this;

	if(m_p != NULL)
		delete []m_p;

	m_p = new T[obj.len];

	len = obj.len;
	for(int i = 0; i
int MyArray::getlen()
{
	return len;
}

template 
ostream & operator<< (ostream &out, const MyArray &obj)
{
	for(int i = 0; i

主函数

#include 
#include "MyArray.h"

using namespace std;

//数组存 自定义类型 , 自定义类型必须要完成的工作
// 1 提供无参构造, 如果有指针, 一定要初始换NULL
// 2 重载 << 操作符, 不重载就无法使用
// 3 重载 = 运算符 进行深拷贝
// 4 静止拷贝构造, 一般用不到

class Student
{
	friend ostream & operator<<(ostream &out,const Student &obj);
public:
	Student()
	{
		id = 0;
		name = NULL;
	}
	Student (int id, char *name)
	{
		this->id = id;
		this->name = new char[20];
		strcpy(this->name, name );
	}

	void print()
	{
		printf("id = %d, name = %s\n", id, name);
	}

	~Student()
	{
		if (name != NULL)
		{
			delete [] name;
			name = NULL;
		}
		id = 0;
	}

	Student & operator=(const Student &obj)
	{
		if(this == &obj)
			return *this;
		if (name != NULL)
			delete []name;

		name = new char[20];

		this->id = obj.id;
		strcpy(name, obj.name);

		return *this;
	}

private:
	int id;
	char *name;
};

ostream & operator<<( ostream &out,const Student &obj)
{
	printf("id = %d, name = %s", obj.id, obj.name);
	return out;
}

int main()
{
	Student s1(10, "wang1");
	Student s2(11, "wang2");
	Student s3(12, "wang3");
	Student s4(13, "wang4");
	Student s5(14, "wang5");

	MyArray a(5);

	a[0] = s1;
	a[1] = s2;
	a[2] = s3;
	a[3] = s4;
	a[4] = s5;

	cout << a << endl;

	system("pause");
	return 0;
}

int main1_1()
{
	MyArray a(10);

	for (int i = 0 ; i b = a,c;

	a[9] = 100;
	c = a;
	cout << a << endl;
	cout << b << endl;
	cout << c << endl;

	system("pause");
	return 0;
}


你可能感兴趣的:(沙僧取金:,第二站,c++)