浅沫记忆 发表于 2021-12-21 22:14:36

[C++] 数组类

主函数

#include "数组类.h"

int main()
{
//数组类 对象arr1
Myarray arr1;

for (int i = 0; i < 10; i++)
{
    arr1.PushBack(i);
}

for (int i = 0; i < arr1.GetSize(); i++)
{
    cout << arr1.GetData(i) << endl;
}

printf("--------------\n");
//数组类 对象arr2
Myarray arr2(arr1);

for (int i = 0; i < arr2.GetSize(); i++)
{
    cout << arr2.GetData(i) << endl;
}

printf("--------------\n");

arr2.SetData(0, 200);

cout << arr2.GetData(0) << endl;
return 0;
}头文件

#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 GetCapacity();

//获取数组大小
int GetSize();

//析构函数
~Myarray();
private:
int m_capacity; //数组容量
int m_size;   //数组大小
int* address; //在堆区开辟的数组的指针
};函数实现

#include "数组类.h"

//默认构造
Myarray::Myarray()
{
this->m_capacity = 100;
this->m_size = 0;
this->address = new int;
}

//有参构造
Myarray::Myarray(int capacity)
{
this->m_capacity = capacity;
this->m_size = 0;
this->address = new int;
}

//拷贝构造
Myarray::Myarray(const Myarray & arr)
{
this->m_capacity = arr.m_capacity;
this->m_size = arr.m_size;
this->address = new int;
for (int i = 0; i < m_size; i++)
{
    this->address = arr.address;
}
}

//尾插法
void Myarray::PushBack(int val)
{
this->address = val;
this->m_size++;
}

//根据位置设置数据
void Myarray::SetData(int pos, int val)
{
this->address = val;
}

//根据位置获取数据
int Myarray::GetData(int pos)
{
return this->address;
}

//获取数组容量
int Myarray::GetCapacity()
{
return this->m_capacity;

}

//获取数组大小
int Myarray::GetSize()
{
return this->m_size;

}

//析构函数
Myarray::~Myarray()
{
if (this->address != NULL)
{
    delete[] this->address;
    this->address = NULL;
}
}

https://blog.51cto.com/u_15335178/4829850
页: [1]
查看完整版本: [C++] 数组类