数组类的封装(代码实现) ——c++
2022/2/8 11:42:33
本文主要是介绍数组类的封装(代码实现) ——c++,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
(强换训练)数组类封装
通过代码实现数组类的封装:
这个时候如果想访问数组的元素,那么就得调用数组的接口
#pragma once #define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; class myarray { public: myarray()//默认构造 可以给100容量 { cout << "构造函数调用" << endl; this->m_Capacity = 100; this->m_Size = 0; this->pAddress = new int[this->m_Capacity]; } myarray(int capacity)//也可以通过有参构造,自己规定容量 { cout << "有参构造函数调用" << endl; this->m_Capacity = capacity; this->m_Size = 0; this->pAddress = new int[this->m_Capacity]; } myarray(const myarray& arr)//拷贝构造函数 { cout << "默认拷贝构造函数调用" << endl; this->m_Capacity = arr.m_Capacity; this->m_Size = arr.m_Size; //前两个成员变量一样,指针能一样,因为防止浅拷贝问题。 this->pAddress = new int[arr.m_Capacity]; //将新的指针创建空间构造完成以后 将数组的值也进行复制 for (int i = 0; i < m_Size; i++) { this->pAddress[i] = arr.pAddress[i]; } } //尾插法 void pushBack(int val)//根据位置设置数据 { this->pAddress[this->m_Size] = val; this->m_Size++; } void setData(int pos, int val)//根据位置设置数据 { this->pAddress[pos] = val; } int getData(int pos)//获取数组的数据 { return this->pAddress[pos]; } int getCapacity()//获取数组的容量 { return this->m_Capacity; } int getSize()//获取数组的容量 { return this->m_Size; } ~myarray()//析构函数,方便等会释放空间 { if (this->pAddress != NULL) { cout << "析构函数调用" << endl; delete[] this->pAddress;//释放数组空间要加[] this->pAddress = NULL; } } private: int m_Capacity;//数组的容量 int m_Size;//数组的大小 int* pAddress;//真实在堆区开辟的数组的指针 }; void test01() { myarray a;//在栈上创建的对象,结束后需要析构函数来释放。 for (int i = 0; i < 10; i++) { a.pushBack(i); } for (int i = 0; i< a.getSize(); i++) { cout << a.getData(i) << endl; } myarray a2(a); for (int i = 0; i < a2.getSize(); i++) { cout << a2.getData(i) << endl; } } int main() { test01(); //cout << "sh" << endl; return 0; }
这篇关于数组类的封装(代码实现) ——c++的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-07fastcgi 是什么-icode9专业技术文章分享
- 2024-10-07fastcgi 的详细使用教程介绍-icode9专业技术文章分享
- 2024-10-07git如何更新单个文件到本地-icode9专业技术文章分享
- 2024-10-07如何使用ASM(Abstract Syntax Tree Manipulation)技术来修改第三方AAR依赖中的函数-icode9专业技术文章分享
- 2024-10-07Activity 跳转时间耗时很长怎么优化解决-icode9专业技术文章分享
- 2024-10-07Androud Toast 有哪些常用的第三方组件-icode9专业技术文章分享
- 2024-10-07在viewmodel中怎么使用 mmkv?-icode9专业技术文章分享
- 2024-10-07MMKV.defaultMMKV() 是单例模式吗?-icode9专业技术文章分享
- 2024-10-04el-table 开启定时器下,表格的选中状态会消失是什么原因-icode9专业技术文章分享
- 2024-10-03如何安装和初始化飞牛私有云 fnOS?-icode9专业技术文章分享