首页 / C++ / C++自定义类型数组
C++自定义类型数组
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C++自定义类型数组,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1753字,纯文字阅读大概需要3分钟。
内容图文
利用函数模板完成对自定义类型的数组的一些简陋操作
#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];
}
内容总结
以上是互联网集市为您收集整理的C++自定义类型数组全部内容,希望文章能够帮你解决C++自定义类型数组所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。