c++小练习

数组类封装

myArray.h

#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class MyArray {
public:
	MyArray();		 //默认构造  可以给100容量
	
	MyArray(int Capacity);		//有参构造

	MyArray(const MyArray& arr);	//拷贝构造

	//尾插法
	void pushBack(int val);
	//根据位置设置数据
	void setData(int pos, int val);
	//根据位置获取数据
	int getData(int pos);
	//获取数组容量
	int getCapacity();
	//获取数组大小
	int getSize();
	//析构
	~MyArray();

private:
	int m_Capacity;  //数组的容量
	int m_Size;		 //数组的大小
	int* pAddress;	 //真实在堆区开辟的数组的指针
};

myArray.cpp

#include "myArray.h"
MyArray::MyArray()		 //默认构造  可以给100容量
{
	cout << "默认构造函数调用" << endl;
	this->m_Capacity = 100;
	this->m_Size = 0;
	this->pAddress = new int[this->m_Capacity];
}
MyArray::MyArray(int Capacity)		//有参构造
{
	cout << "有参构造函数调用" << endl;
	this->m_Capacity = 100;
	this->m_Size = 0;
	this->pAddress = new int[this->m_Capacity];
}
MyArray::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 MyArray::pushBack(int val)
{
	this->pAddress[this->m_Size] = val;
	this->m_Size++;
}
//根据位置设置数据
void MyArray::setData(int pos, int val)
{
	this->pAddress[pos] = val;
}
//根据位置获取数据
int MyArray::getData(int pos)
{
	return this->pAddress[pos];
}
//获取数组容量
int MyArray::getCapacity()
{
	return this->m_Capacity;
}
//获取数组大小
int MyArray::getSize()
{
	return this->m_Size;
}
//析构
MyArray::~MyArray()
{
	if (this->pAddress != NULL)
	{
		cout << "析构函数调用" << endl;
		delete [] this->pAddress;
		this->pAddress = NULL;
	}
}

main.cpp

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
#include "myArray.h"

void test01()
{
	MyArray arr;
	for (int i = 0; i < 10; i++)
	{
		arr.pushBack(i);
	}
	for (int i = 0; i < arr.getSize(); i++)
	{
		cout << arr.getData(i) << endl;
	}
	MyArray arr2(arr);
	for (int i = 0; i < arr2.getSize(); i++)
	{
		cout << arr2.getData(i) << endl;
	}
	arr.setData(0, 1000);
	for (int i = 0; i < arr.getSize(); i++)
	{
		cout << arr.getData(i) << endl;
	}
}

int main()
{
	test01();

	system("pause");
	return EXIT_SUCCESS;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值