实现自定义数组, 重载[] , << , = 运算符 , 并且数组可以使用自定义类
头文件
#ifndef __MYARRAY_H__
#define __MYARRAY_H__
#include <iostream>
using namespace std;
template <typename T>
class MyArray
{
friend ostream & operator<< <T>( ostream &out, const MyArray<T> &obj);
public:
MyArray ();
MyArray (int len);
MyArray (const MyArray<T> &obj);
~MyArray();
public:
T & operator[](int index);
MyArray<T> & operator=(const MyArray &obj);
public:
int getlen();
private:
T *m_p ;
int len;
};
template <typename T>
MyArray<T>::MyArray()
{
m_p = NULL;
}
template <typename T>
MyArray<T>::MyArray (int len)
{
this->len = len;
m_p = new T[len];
}
template <typename T>
MyArray<T>::MyArray (const MyArray<T> &obj)
{
len = obj.len;
m_p = new T[len];
for(int i = 0; i<len ; i++)
{
m_p[i] = obj.m_p[i];
}
}
template <typename T>
MyArray<T>::~MyArray()
{
if (m_p != NULL)
delete [] m_p;
len = 0;
}
template <typename T>
T & MyArray<T>::operator[](int index)
{
return m_p[index];
}
template <typename T>
MyArray<T> & MyArray<T>::operator=(const MyArray<T> &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<len ; i++)
{
m_p[i] = obj.m_p[i];
}
return *this;
}
template <typename T>
int MyArray<T>::getlen()
{
return len;
}
template <typename T>
ostream & operator<< (ostream &out, const MyArray<T> &obj)
{
for(int i = 0; i<obj.len ; i++)
{
cout << obj.m_p[i] << "\n";
}
//cout << endl;
return out;
}
#endif //__MYARRAY_H__
主函数
#include <iostream>
#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<Student> 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<int> a(10);
for (int i = 0 ; i<a.getlen(); i++)
{
a[i] = i;
}
MyArray<int> b = a,c;
a[9] = 100;
c = a;
cout << a << endl;
cout << b << endl;
cout << c << endl;
system("pause");
return 0;
}