我使用的是clion,先定义一个头文件
头文件中定义了MyArray类的成员对象和方法如下
#pragma once
#include<iostream>
using namespace std;
#ifndef BLUEBRIDGE2018_MYARRAY_H
#define BLUEBRIDGE2018_MYARRAY_H
class MyArray{
private:
int mCapacity{};//数组容量
int mSize{};//数组大小
int*pAddress{};//指向堆区的数组指针
public:
//默认构造
MyArray();
//有参构造函数,用户指定容量初始化
MyArray(int capacity);
//拷贝构造
MyArray(const MyArray &arr);
//用户操作接口
//根据位值添加元素
int SetData(int pos, int val);
//获得指定位值数据
int GetData(int pos);
//尾插法
void PushBack(int val);
//获取长度
int GetSize();
//获取容量
int getCapacity();
//析构函数,释放数组空间
~MyArray();
};
#endif //BLUEBRIDGE2018_MYARRAY_H
接下来创建一个同名的源文件,再其中对上面定义的方法进行初始化
#include "MyArray.h"
MyArray::MyArray() {
cout<<"默认构造函数的调用"<<endl;
this->mCapacity=100;
this->mSize=0;
this->pAddress=new int[this->mCapacity];
}
MyArray::MyArray(int capacity) {
cout<<"有参构造函数调用"<<endl;
this->mCapacity=capacity;
this->mSize=0;
this->pAddress=new int[this->mCapacity];
}
MyArray::MyArray(const MyArray &arr) {
cout<<"拷贝构造函数调用"<<endl;
this->mCapacity=arr.mCapacity;
this->mSize=arr.mSize;
this->pAddress=new int[this->mCapacity];
for(int i=0;i<mSize;i++){
this->pAddress[i]=arr.pAddress[i];
}
}
int MyArray::SetData(int pos, int val) {
return this->pAddress[pos]=val;
}
int MyArray::GetData(int pos) {
return this->pAddress[pos];
}
void MyArray::PushBack(int val) {
this->pAddress[this->mSize]=val;
this->mSize++;
}
int MyArray::GetSize() {
return this->mSize;
}
int MyArray::getCapacity() {
return this->mCapacity;
}
MyArray::~MyArray() {
cout<<"析构函数调用"<<endl;
if(this->pAddress!=NULL){
delete [] this->pAddress;
this->pAddress=NULL;
}
}
在写同名源文件的时候,有一个快捷方式,在写上#include"MyArray.h"
以后可以快速拷贝待初始化成员函数,像下面这样
操作的方法是在MyArray.h文件内,光标放在待拷贝的函数名上,按ctrl+home键,出现黄色小灯泡后,下拉选筐中选择第一项
接下来就可以新建一个test源文件来测试这个类了
#include "MyArray.h"
void test01(){
MyArray *arr=new MyArray(10);
delete arr;
MyArray arr2;
for(int i=0;i<10;i++){
arr2.PushBack(i+100);
}
MyArray arr3(arr2);
for(int i=0;i<10;i++){
cout<<"位值为"<<i<<"的元素为"<<arr3.GetData(i)<<endl;
}
cout<<"数组的容量为:"<<arr3.getCapacity()<<endl;
cout<<"数组的大小为:"<<arr3.GetSize()<<endl;
}
int main(){
test01();
return 0;
}
输出结果如下: