实现数组的模板类

实现数组的模板类

Myarray1.h

#ifndef _ARRAY_
#define _ARRAY_

#include 
using namespace std;

template 
class Myarray1
{
private:
	int m_len;
	T *m_data;
public:
	Myarray1();
	~Myarray1();
	Myarray1(int l);
	Myarray1(const Myarray1 &a);

	friend ostream &operator <<(ostream &out, const Myarray1 &a)
	{	
		for (int i = 0; i < a.m_len; i++)
		{
			out << a.m_data << " ";
		}

		return out;
	}

	T &operator [](int index);
};


#endif

Myarray1.cpp

#include "Myarray1.h"
template 
Myarray1::Myarray1()
{
	m_len = 1;
	m_data = new T[m_len + 1];
	cout << "Myarray1() constuctor ok~" << endl;
}

template 
Myarray1::~Myarray1()
{
	if (m_data != NULL)
		delete[] m_data;
	cout << "Myarray1() destuctor ok~" << endl;
}

template 
Myarray1::Myarray1(int l)
{
	m_len = l;
	m_data = new T[m_len + 1];
	cout << "Myarray1(int l) constuctor ok~" << endl;
}

template 
Myarray1::Myarray1(const Myarray1 &a)
{
	m_len = a.m_len;
	m_data = new T[m_len + 1];

	for (int i = 0; i < m_len; i++)
	{
		m_data[i] = a.m_data[i];
	}

	cout << "Myarray1(const Myarray &a) constuctor ok~" << endl;
}

template 
T &Myarray1::operator [](int index)
{
	return m_data[index];
}

main.cpp

#include 
#include "Myarray1.cpp"
using namespace std;

int main()
{
	Myarray1 ma1;

	Myarray1 ma2(5);

	cout << ma2 << endl;


	system("pause");
	return 0;
}

 

你可能感兴趣的:(学习,生活,C++)