评论

收藏

[C++] [C++] 数组类

编程语言 编程语言 发布于:2021-12-21 22:14 | 阅读数:277 | 评论:0

主函数
#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[this->m_capacity];
}
//有参构造
Myarray::Myarray(int capacity)
{
  this->m_capacity = capacity;
  this->m_size = 0;
  this->address = new int[this->m_capacity];
}
//拷贝构造
Myarray::Myarray(const Myarray & arr)
{
  this->m_capacity = arr.m_capacity;
  this->m_size = arr.m_size;
  this->address = new int[arr.m_capacity];
  for (int i = 0; i < m_size; i++)
  {
  this->address[i] = arr.address[i];
  }
}
//尾插法
void Myarray::PushBack(int val)
{
  this->address[this->m_size] = val;
  this->m_size++;
}
//根据位置设置数据
void Myarray::SetData(int pos, int val)
{
  this->address[pos] = val;
}
//根据位置获取数据
int Myarray::GetData(int pos)
{
  return this->address[pos];
}
//获取数组容量
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;
  }
}

关注下面的标签,发现更多相似文章