テンプレートクラス汎用配列の実装
カスタム配列を実装し、[],<,=演算子を再ロードし、配列はカスタムクラスを使用できます.
ヘッダファイル
しゅかんすう
ヘッダファイル
#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<id = id;
this->name = new char[20];
strcpy(this->name, name );
}
void print()
{
printf("id = %d, name = %s
", 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< 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;
}