01数组类.cpp:
#pragma warning(disable:4996)
//2022年10月2日20:33:53
#include <iostream>
using namespace std;
#include "MyArray.h"
void printMyArray(MyArray &arr)
{
for(int i = 0; i < arr.Size(); i++)
{
cout << arr.Get(i) << " ";
}
cout << endl;
}
void test01()
{
MyArray arr( 20, 1 );
printMyArray( arr );
//修改数组中的值
for(int i = 0; i < arr.Size(); i++)
{
arr.Get( i ) = i + 100;
}
printMyArray( arr );
//指定位置修改值
arr.Set( 2, 0 );
printMyArray( arr );
//测试是否发生浅拷贝
MyArray arr2 = arr;
printMyArray( arr );
}
int main()
{
test01();
system("pause");
return EXIT_SUCCESS;
}
MyArray.cpp
#include "MyArray.h"
MyArray::MyArray()
{
this->mCapacity = 20;
this->mSize = 0;
this->pArray = new int[this->mCapacity];
for( int i = 0; i < this->mCapacity; i++ )
{
this->pArray[i] = 0;
}
}
MyArray::~MyArray()
{
if( this->pArray != NULL )
{
delete[] this->pArray;
this->pArray = NULL;
}
}
MyArray::MyArray(const MyArray &arr)
{
this->mCapacity = arr.mCapacity;
this->mSize = arr.mSize;
//1.申请空间
this->pArray = new int[arr.mCapacity];
//2.拷贝数据
for(int i = 0; i < this->mSize; i++)
{
this->pArray[i] = arr.pArray[i];
}
}
MyArray::MyArray(int capacity, int val)
{
this->mCapacity = capacity;
this->mSize = capacity;
this->pArray = new int[capacity];
for(int i = 0; i < this->mSize; i++)
{
this->pArray[i] = val;
}
}
//头插
void MyArray::PushFront(int val)
{
}
//尾插
void MyArray::PushBack(int val)
{
}
//头删
void MyArray::PopFront()
{
}
//尾删
void MyArray::PopBack()
{
}
//获取数组元素个数
int MyArray::Size()
{
return this->mSize;
}
//获取数组容量
int MyArray::Capacity()
{
return this->mCapacity;
}
//指定位置插入元素
void MyArray::Insert(int pos, int val)
{
}
//获取指定位置的值
int &MyArray::Get(int pos)
{
return this->pArray[pos];
}
//在指定位置修改值
void MyArray::Set(int pos, int val)
{
if(pos < 0 || pos > this->mCapacity - 1)
{
return;
}
this->pArray[pos] = val;
}
MyArray.h
#pragma once
#include<iostream>
using namespace std;
class MyArray
{
public:
MyArray();
MyArray(const MyArray &arr);
MyArray(int capicity, int val = 0);
~MyArray();
//头插
void PushFront(int val);
//尾插
void PushBack(int val);
//头删
void PopFront();
//尾删
void PopBack();
//获取数组元素个数
int Size();
//获取数组容量
int Capacity();
//指定位置插入元素
void Insert(int pos, int val);
//获取指定位置的值
int& Get(int pos);
//在指定位置修改值
void Set(int pos, int val);
private:
int * pArray;//指向堆区空间,储存数据
int mSize;//元素个数
int mCapacity;//容量
};
输出结果:
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
100 101 0 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
100 101 0 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
请按任意键继续. . .
标签:27,val,int,pArray,void,MyArray,数组,mCapacity
From: https://www.cnblogs.com/codemagiciant/p/16751034.html