|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <iostream>
using namespace std;
template <class T>
class Array
{
private:
T* alist;
int size = 0;
public:
Array(int sz);
Array(const Array<T>& a);
~Array();
void display();
T& operator[](int i);
Array<T>& operator =(Array<T>& a);
operator T*(void)const;
};
template <class T>
Array<T>::Array(int sz)
{
if (sz <= 0)
{
cout << "Array size error." << endl;
exit(1);
}
else
{
size = sz;
alist = new T[size];
if (alist = NULL)
{
cout << "Array memory allocation error." << endl;
exit(1);
}
}
}
template <class T>
Array<T>::Array(const Array<T>& a)
{
size = a.size;
list = new T[size];
if (list = NULL)
{
cout << "Array memory allocation error." << endl;
exit(1);
}
int n = size;
T* pointer1 = list;
T* pointer2 = a.alist;
while (n--)
{
*pointer1++ = *pointer2++;
}
}
template <class T>
Array<T>::~Array()
{
delete[] alist;
size = 0;
}
template <class T>
void Array<T>::display()
{
for (int i = 0; i < size; i++)
{
cout << setw(5) << *(alist + i);
}
cout << endl;
}
template <class T>
T& Array<T>::operator[](int i)
{
if (i < 0 || i > size - 1)
{
cout << "Array[]size error." << endl;
exit(1);
}
return alist[i];
}
template <class T>
Array<T>& Array<T>::operator=(Array<T>& a)
{
int n = a.szie;
if (size != n)
{
delete[] alist;
alist = new T[n];
if (alist = NULL)
{
cout << "Array memory allocation error." << endl;
exit(1);
}
size = n;
}
T* pointer1 = alist;
T* pointer2 = a.alist;
while (n--)
{
*pointer1++ = *pointer2++;
}
return *this;
}
template <class T>
Array<T>::operator T*(void)const
{
return alist;
}
int main(void)
{
Array<int> a(2);
a[1] = 10;
cout << a[1];
return 0;
}
file:///C:\Users\Administrator\AppData\Roaming\Tencent\Users\316550592\QQ\WinTemp\RichOle\OSEP78H4C94IE$SIFZPH]FG.png
|
-
|