编辑代码

#include <iostream>
using namespace std;
class MyArray{
public:
    MyArray(){
        cout<<"默认构造的调用"<<endl;
        this->pAddress=new int[this->m_Capacity];
        this->m_Size=0;
        this->m_Capacity=100;
    }
    MyArray(int Capacity){
        cout<<"有参构造的调用"<<endl;
        this->pAddress=new int[this->m_Capacity];
        this->m_Size=0;
        this->m_Capacity=Capacity;
    }
    MyArray(const MyArray& array){
        cout<<"拷贝构造的调用"<<endl;
        this->pAddress=new int[array.m_Capacity];
        this->m_Size=array.m_Size;
        this->m_Capacity=array.m_Capacity;
    }
    ~MyArray(){
        cout<<"析构的调用"<<endl;
        if(this->pAddress!=NULL){
            delete[] this->pAddress;
            this->pAddress=NULL;
        }
    }
    //提供尾插法
    void push_Back(int val){
        this->pAddress[this->m_Size]=val;
        this->m_Size++;
    }
    //根据索引获取值
    int getData(int index){
        return this->pAddress[index];
    }
    //根据索引设置值
    void setData(int val,int index){
        this->pAddress[index]=val;
    }
    //获取数组的大小
    int getSize(){
        return this->m_Size;
    }
    int getCapacity(){
        return this->m_Capacity;
    }
private:
    int* pAddress;
    int m_Size;
    int m_Capacity;
};
void test01(){
    //在堆区创建数组
    MyArray* array1=new MyArray(30);//new方法的有参构造
    MyArray* array2=new MyArray(*array1);//new方法的拷贝构造
    MyArray* array3=array1;//一个指针的声明,不会调用构造
    MyArray array4=*array1;//返回对象本身,切勿在释放后使用,也会调用拷贝构造
    //MyArray* array5(array1);
    //尾插的测试
    for(int i=0;i<10;i++){
        array1->push_Back(i);
    }
    //获取数值的测试
    for(int i=0;i<10;i++){
        cout<<array1->getData(i)<<endl;
    }
    //设置数值的测试
    array1->setData(1000,0);
    cout<<"现在array1[0]的值为:"<<array1->getData(0)<<endl;
    //获取所创建的数组的大小和容量
    cout<<"array1的数组大小为:"<<array1->getSize()<<endl;
    cout<<"array1的数组容量为:"<<array1->getCapacity()<<endl;
    //cout<<array4[0]<<endl;不能直接通过对象名访问数组元素
}
int main() {
    //JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。 
	//cout << "Hello JSRUN!   \n\n         - from C++ ." << endl;
    test01();
	return 0;
}