ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

数组类的封装(代码实现) ——c++

2022-02-08 11:03:56  阅读:142  来源: 互联网

标签:Capacity cout int c++ pAddress 数组 封装 Size


(强换训练)数组类封装

通过代码实现数组类的封装

这个时候如果想访问数组的元素,那么就得调用数组的接口

#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;
}

标签:Capacity,cout,int,c++,pAddress,数组,封装,Size
来源: https://blog.csdn.net/qq_51399192/article/details/122819957

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有