MyArray.h
#pragma once
#include <iostream>
using namespace std;
class MyArray {
public:
MyArray();
MyArray(int capacity);
MyArray(const MyArray& arr);
~MyArray();
int getData(int index);
void setData(int index, int val);
void PushBack(int value);
int getSize();
int getCapacity();
private:
int m_Capacity; //数组容量
int m_Size; //数组大小
int *pAddress;//指向真正存储数据的指针
};
MyArray.cpp
#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];
if (arr.m_Size != 0) {
for (int i = 0; i < arr.m_Size; i++) {
this->pAddress[i] = arr.pAddress[i];
}
}
}
MyArray::~MyArray()
{
if (this->pAddress != NULL) {
cout << "析构调用" << endl;
delete[] this->pAddress;
this->pAddress = NULL;
}
}
int MyArray::getData(int index)
{
return this->pAddress[index];
}
void MyArray::setData(int index, int val)
{
this->pAddress[index] = val;
}
void MyArray::PushBack(int value)
{
//判断越界? 用户自己处理
this->pAddress[this->m_Size] = value;
this->m_Size++;
}
int MyArray::getSize()
{
return this->m_Size;
}
int MyArray::getCapacity()
{
return m_Capacity;
}
test.cpp
#include<iostream>
#include<string>
#include "MyArray.h"
using namespace std;
void test01() {
//堆区创建数组
MyArray *array = new MyArray(30);
MyArray *array2 = new MyArray(*array);//new方式指定调用拷贝构造
MyArray array3 = *array;//构造函数返回的本体
//MyArray * array4 = array; //这个是声明一个指针 和array执行的地址相同,所以不会调用拷贝构造
delete array;
//尾插法测试
for (int i = 0; i < 5; i++) {
array2->PushBack(i);
}
//获取数据测试
for (int i = 0; i < 5; i++) {
cout << array2->getData(i) << " ";
}
cout << endl;
//设置值测试
array3.setData(3,78);
cout << array3.getData(3) << endl;
//获取数组大小
cout << array2->getSize() << endl;
//获取数组容量
cout << array2->getCapacity() << endl;
}
int main(){
test01();
system("pause");
return 0;
}