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

25 篇文章 0 订阅
3 篇文章 0 订阅

(强换训练)数组类封装

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

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

#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;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是小明同学啊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值