实现:类模板的数组类封装

前言:不管再这么讨厌综合案例,但是不得不说学着做一次综合案例胜过自己看千万次

示例代码:

Myarray.hpp

#include<string>
#include<iostream>
using namespace std;
template<class t>
class Myarray {
public:
Myarray(int capacity) {
//cout << "这是构造函数的调用" << endl;
this->m_size = 0;
this->m_capacity = capacity;
m_array = new t[this->m_capacity]; // m_array指针堆区开辟的数组,容量位m_capacity
}
~Myarray() { //定义析构函数,结束之后进行内存释放的操作
if (this->m_array != NULL) { //首先进行判断是否为空
//cout << "这是析构函数的调用" << endl;
delete[] m_array ; //释放内存
this->m_array = NULL; //防止成为野指针
this->m_size = 0; //接下来的两步其实可有可无
this->m_capacity = 0;
}
}
//拷贝函数需要进行解决的是深浅拷贝引发的内存问题
Myarray(const Myarray & arr) { //传参为arr
//cout << "这里拷贝函数的调用" << endl;
this->m_capacity = arr.m_capacity;
this->m_size = arr.m_size;
this->m_array = new t[this->m_capacity];//唯一会引发内存问题的就在这,这里自己开辟新的内存其数据类型为t到堆区赋值
for (int i = 0; i < this->m_size; i++)
{
//如果T为对象,而且还包含指针,必须需要重载 = 操作符,因为这个等号不是 构造 而是赋值,
// 普通类型可以直接= 但是指针类型需要深拷贝
this->m_array[i] = arr.m_array[i];
}
}
//operator= 引起的深浅拷贝的问题我们也需要解决
Myarray& operator=(const Myarray & arr) { //返回的对象为Myarray的引用,原因是a=b=c的 连续赋值的问题
//cout << "这里operator=调用" << endl;
if (this->m_array != NULL) { //首先进行判断是否为空
delete[] m_array; //释放内存
this->m_size = 0; //接下来的两步其实可有可无
this->m_capacity = 0;
}
//然后在得到赋值右边的数据内容
this->m_capacity = arr.m_capacity;
this->m_size = arr.m_size;
this->m_array = new t[this->m_capacity];
//然后再拿到指针中的数据
for (int i = 0; i < this->m_size; i++) {
this->m_array[i] = arr.m_array[i];
}
return *this; //返回当前对象本身,因为this 本身就是 Myarray * const a
}
friend void to_print(Myarray<t> & m) {
for (int i = 0; i < m.m_size; i++) {
cout << m.m_array[i] << " ";
}
}
//尾插法的实现
void tail_in(t num) {
if (this->m_size == this->m_capacity) {
cout << "存储内容已满" << endl;
}else {
this->m_array[this->m_size] = num;
this->m_size++;
}
}
//尾删法的实现
void tail_out() {
if (this->m_size == 0) {
cout << "存储内容已空" << endl;
}
else {
this->m_size--; //只实现逻辑删除
}
}
//获取数组的容量和大小
void to_get_size() {
cout << "当前数组的存储容量为: " << this->m_capacity << endl;
cout << "当前数组的存储大小为: " << this->m_size << endl;
}
private:
int m_size; //具体存放的数量
int m_capacity; //存放的容量
t * m_array; //定义的一个存放数组类型t的指针
};

1.cpp

#include "Myarray.hpp"
void test01() { //函数开辟栈区,测试析构
Myarray<int> arr1(5);
arr1.tail_in(5);
arr1.tail_in(10);
arr1.tail_out();
to_print(arr1);
}
int main() {
test01();
system("pause");
return 0;
}
posted @   zpchcbd  阅读(365)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示