C++自定义数组

#ifndef _MYARRAY_H_
#define _MYARRAY_H_
#include<iostream>
#include<string>

template<class T>
class Myarray {

public:
//默认构造
Myarray(int capcity);
//拷贝构造
Myarray(const Myarray<T>& arr);
//重载[]
T& operator[](int index);
//重载=
Myarray<T>& operator=(const Myarray<T>& arr);
//在数组后面追加元素
void Pushback(T& data);
//对右值去引用
void Pushback(T&& data);
~Myarray();


public:
int m_Capacity;//总共能存多大的数据
int m_Size;//现在的数据尺寸
T* p_Addr;//数据指针
private:

};

 

 

template<class T>
Myarray<T>::Myarray<T>(int capcity) {
this->m_Capacity = capcity;
this->m_Size = 0;
this->p_Addr = new T[this->m_Capacity];


}
//拷贝构造
template<class T>
Myarray<T>::Myarray<T>(const Myarray<T>& arr) {
this->m_Size = arr.m_Size;
this->m_Capacity = arr.m_Capacity;
this->p_Addr = new T[this->m_Capacity];
for (int i = 0; i < this->m_Size; i++) {
this->p_Addr[i] = arr.p_Addr[i];
}
}

template<class T>
T& Myarray<T>::operator[](int index) {
return this->p_Addr[index];

}

template<class T>
Myarray<T>& Myarray<T>::operator=(const Myarray<T>& arr) {
if (this->p_Addr != NULL) {
delete[] this->p_Addr;
}
this->m_Size = arr.m_Size;
this->m_Capacity = arr.m_Capacity;
this->p_Addr = new T[this->m_Capacity];
for (int i = 0; i < this->m_Size; i++) {
this->p_Addr[i] = arr.p_Addr[i];
}

return *this;
}

template<class T>
void Myarray<T>::Pushback(T& data) {

//先判断容器中是否有位置
if (this->m_Size >= this->m_Capacity) {
return;
}
this->p_Addr[this->m_Size] = data;
this->m_Size++;
}

template<class T>
void Myarray<T>::Pushback(T&& data) {

//先判断容器中是否有位置
if (this->m_Size >= this->m_Capacity) {
return;
}
this->p_Addr[this->m_Size] = data;
this->m_Size++;
}

template<class T>
Myarray<T>::~Myarray() {
if (this->p_Addr != NULL) {
delete[] this->p_Addr;

}

}


#endif // !_MYARRAY_H_

 

posted @   水木清扬  阅读(873)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示