C++自定義型別陣列
阿新 • • 發佈:2021-02-09
利用函式模板完成對自定義型別的陣列的一些簡陋操作
#include<iostream>
#include<string>
using namespace std;
template<class T>//類模組
class Array
{
public:
Array(int n)//建構函式
{
m_capacity = n;
this->m_size = 0;
p = new T[n];
}
Array(const Array& a)//拷貝建構函式:防止淺拷貝
{
this->m_capacity = a.m_capacity;
this->m_size =a.m_size;
this->p = new T[a.m_capacity];
for (int i = 0; i < a.m_size; ++i)
this->p[i] = a.p[i];
}
bool operator==(const Array& a)//過載==:為了判斷是否是自身==自身
{
if (this->m_capacity != a.m_capacity || this->m_size != a.m_size)
return false;
for (int i = a.m_size; i < a.m_size; ++i)
if (this->p[i] != a.p[i])
return false;
return true;
}
Array& operator=(const Array& a)//過載=:深拷貝
{
if (*this == a)//若是自身等於自身,則直接返回自身
return *this;
if (this->p != NULL)//先判斷原來堆區中是否有資料,若有資料則先釋放
{
delete[] p;
p = NULL;
this ->m_capacity = 0;
this->m_size = 0;
}
this->m_capacity = a.m_capacity;
this->m_size = a.m_size;
this->p = new T[a.m_capacity];
for (int i = 0; i < a.m_size; ++i)
this->p[i] = a.p[i];
return *this;
}
T& operator[](int index)//過載[]:達到利用下標可以訪問元素
{
if (index >= m_size)
cout << "溢位!";
return this->p[index];
}
void Create(const T &x)//尾插法
{
if (this->m_size == this->m_capacity)
{
cout << "陣列容量已滿,無法再插入" << endl;
return;
}
this->p[this->m_size] = x;
++m_size;
}
void deleteArray()//尾刪法
{
if (this->m_size == 0)
{
cout << "陣列為空" << endl;
return;
}
--this->m_size;
}
int getsize()//獲得大小
{
return m_size;
}
int getcapacity()
{
return m_capacity;//獲得容量
}
~Array()//析構
{
if (p != NULL)
{
delete [] p;
p = NULL;
}
}
private:
int m_size;//大小
int m_capacity;//容量
T* p ;//指向陣列
};
int main()//測試案列可以自定義一個類來進行測試,此處粗略測試一下
{
Array<char> a(10);
Array<char> b(1000);
b = a;
b.Create(97);
cout << b[1];
}