#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class MyArray
{
public:
MyArray();
MyArray(int capacity);
MyArray(const MyArray & arr);
void pushBack(int val);
void setData(int pos, int val);
int getData(int pos);
int getCapcity();
int getSize();
~MyArray();
int& operator[](int index);
private:
int m_Capacity;
int m_Size;
int *pAddress;
};
#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);
cout << "arr 0号位置数据为: " << arr.getData(0) << endl;
for (int i = 0; i < 10; i++)
{
cout << arr.getData(i) << endl;
}
cout << "数组容量为: " << arr.getCapcity() << endl;
cout << "数组大小为: " << arr.getSize() << endl;
cout << "---------------------" << endl;
arr[0] = 10000;
cout << arr[0] << endl;
}
int main(){
test01();
system("pause");
return EXIT_SUCCESS;
}
#include "myArray.h"
MyArray::MyArray()
{
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 = capacity;
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::getCapcity()
{
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;
}
}
int& MyArray::operator[](int index)
{
return this->pAddress[index];
}