アレイ型パッケージ

サブファイル書き込み

MyArray.h

#pragma once
#include<iostream>
using namespace std;

class MyArray
{
public:
	MyArray(); //默认构造  构造100容量
	MyArray(int capacity);
	MyArray(const MyArray& myArray);
	~MyArray();

	//尾插数据
	void pushBack(int val);
	//获得数据
	int getData(int index);
	//根据索引设置值
	void setData(int index,int val);
	//[]运算符重载
	int& operator[](int index);
private:
	int *pAddress;  //指向堆中真正的数组
	int m_Size;     //数组的大小
	int	m_Capacity; //数组的容量
};

MyArray.cpp

#include "MyArray.h"

//默认构造
MyArray::MyArray()
{
	cout<<"默认构造调用"<<endl;
	this->pAddress = new int[100];
	this->m_Capacity=100;
	this->m_Size=0;

}
//有参构造
MyArray::MyArray(int capacity)
{
	cout<<"有参构造调用"<<endl;
	this->pAddress = new int[capacity];
	this->m_Capacity=capacity;
	this->m_Size=0;
}
//拷贝构造
MyArray::MyArray(const MyArray& myArray)
{
	cout<<"拷贝构造调用"<<endl;
	this->pAddress=new int[myArray.m_Capacity];
	this->m_Size  = myArray.m_Size;
	this->m_Capacity=myArray.m_Capacity;
	
	for(int i=0;i<myArray.m_Size;i++)
	{
		this->pAddress[i]=myArray.pAddress[i];
	}
}
//析构
MyArray::~MyArray()
{
	cout<<"析构调用"<<endl;
	if(pAddress !=NULL)
	{
		delete [] pAddress;
		pAddress=NULL;
	}
}

//尾插数据
void MyArray::pushBack(int val)
{
	//越界就让他崩 ,系统数组也是直接让他崩
	this->pAddress[m_Size] = val;
	m_Size++;
}
//获得数据
int MyArray::getData(int index)
{
	return pAddress[index];
}
//根据索引设置值
void MyArray::setData(int index,int val)
{
	pAddress[index] = val;
}
//[]运算符重载
int&  MyArray::operator[](int index)
{
	return pAddress[index];
}

main.cppに

#include<iostream>
using namespace std;
#include"MyArray.h"

void test01()
{
	MyArray *p =new MyArray(30);
	MyArray arr(*p);
	for(int i=0; i<10 ;i++)
	{
		p->pushBack(i);
	}
	for(int i=1;i<10;i++)
	{
		cout<<p->getData(i)<<endl;
	}
	p->setData(0,1000);
	cout<<p->getData(0)<<endl;

	//测试【】运算符重载
	MyArray array3(20);
	array3.setData(0,10000);
	cout<<array3[0]<<endl;
	array3[0]= 100;
	cout<<array3[0]<<endl;
}
int main()
{
	test01();
	return 0;
}
公開された38元の記事 ウォン称賛13 ビュー4340

おすすめ

転載: blog.csdn.net/YanWenCheng_/article/details/103928300