C++ 自己实现 数组的部分功能

  1. MyArr.h
#pragma once
#include <iostream>
using namespace std;

class MyArray 
{
public:
	//默认构造函数
	MyArray();
	//有参构造函数,可自己指定容量初始化
	explicit MyArray(int capacity);
	//拷贝构造
	MyArray(const MyArray& array);
	//根据位置添加元素
	void SetDate(int pos, int val);
	//获得指定位置的数据
	int GetData(int pos);
	//尾插法
	void PushBack(int val);
	//获得长度
	int GetLength();
	//析构函数,释放数组空间
	~MyArray();

private:
	int mCapacity;  //数组可容纳多少个元素
	int nSize;      //当前数组中元素的个数
	int* pAddress;  //指向数组的首地址
};
  1. MyArr.cpp
#include "MyArr.h"

//默认构造函数
MyArray::MyArray()
{
	cout << "默认构造函数的调用" << endl;
	this->mCapacity = 0;   //数据的初始化
	this->nSize = 0;
	pAddress = new int[mCapacity];
}

//有参构造函数,可自己指定 容量、初始化
MyArray::MyArray(int capacity)
{
	cout << "有参构造函数的调用" << endl;
	this->mCapacity = capacity;
	pAddress = new int[mCapacity];
	nSize = 0;
	pAddress[capacity] = { 0 };
}

//拷贝构造
MyArray::MyArray(const MyArray& array)
{
	cout << "拷贝构造函数的调用" << endl;
	pAddress = new int[array. mCapacity];
	this->mCapacity = array.mCapacity;

	for (int i = 0; i < array.mCapacity; ++i)
	{
		this->pAddress[i] = array.pAddress[i];
	}
}

//根据位置添加元素
void MyArray::SetDate(int pos, int val)
{
	if (pos<0 || pos>mCapacity - 1)
	{
		return;
	}

	for (int i = pos; i < mCapacity - 1; ++i)
	{
		this->pAddress[i + 1] = pAddress[i];
	}
	this->pAddress[pos] = val;
	this->nSize++;
}

//获得指定位置的数据
int MyArray::GetData(int pos)
{
	if (pos<0 || pos>mCapacity - 1)
	{
		return -1;
	}
	return this->pAddress[pos];

}

//尾插法
void MyArray::PushBack(int val)
{
	if (nSize == mCapacity)
	{
		return;
	}
	this->pAddress[nSize] = val;
	this->nSize++;
}

//获得长度
int MyArray::GetLength()
{
	return this->nSize;
}

//析构函数,释放数组空间
MyArray::~MyArray()
{
	cout << "析构函数的调用" << endl;
	if (pAddress != NULL)
	{
		delete[] pAddress;
	}
	pAddress = NULL;
}
  1. 数组类的封装.cpp
#include"MyArr.h"

void test()
{
	MyArray* p = new MyArray(30);
	MyArray p2(*p);

	for (int i = 0; i < 10; ++i)
	{
		p2.PushBack(i);
	}

	for (int i = 0; i < p2.GetLength(); ++i)
	{
		cout << p2.GetData(i) << endl;
	}
}

int main()
{
	test();

	system("pause");
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值