c++实现顺序表的相关操作

Myarray.h文件

#pragma once

#include<iostream>

using namespace std;

class MyArray
{
public:
	MyArray();//默认构造 默认100容量
	MyArray(int capacity);
	MyArray(const MyArray& array);

	~MyArray();

	//尾插法
	void Push_Back(int val);

	//根据索引获取值
	int getData(int index);

	//根据索引设置值
	void setData(int index, int val);

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

	//获取数组容量
	int getCapacity();

private:
	int *pAddress;//指向真正存储数据的指针
	int m_Size;//数组的大小
	int m_Capacity;//数组容量
};

Myarray.cpp

#include"Myarray.h"

//默认构造
MyArray::MyArray()
{
	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 & array)
{
	cout << "拷贝构造的调用" << endl;
	this->pAddress = new int[array.m_Capacity];
	this->m_Size = array.m_Size;
	this->m_Capacity = array.m_Capacity;

	for (int i = 0; i < array.m_Size; i++)
	{
		this->pAddress[i] = array.pAddress[i];
	}

}

//析构
MyArray::~MyArray()
{
	if (this->pAddress != NULL)
	{
		cout << "析构函数的调用" << endl;
		delete[]this->pAddress;
		this->pAddress = NULL;
	}
}

void MyArray::Push_Back(int val)
{
	//判断越界?用户自己处理
	this->pAddress[this->m_Size] = val;
	this->m_Size++;
}

int MyArray::getData(int index)
{
	return this->pAddress[index];
}

void MyArray::setData(int index, int val)
{
	this->pAddress[index] = val;
}

int MyArray::getCapacity()
{
	return this->m_Capacity;
}
int MyArray::getSize()
{
	return this->m_Size;
}

test.cpp

#include"Myarray.h"

void test01()
{
	//堆区创建数组
	MyArray *array = new MyArray(30);

	MyArray *array2=new MyArray(*array);//new方式指定拷贝构造

	MyArray array3 = *array2;  //构造函数返回的本体

	//MyArray *array4 = array; //这声明一个指针和array执行的地址相同,所以不会调用拷贝构造


	delete array;

	//尾插法的测试
	for (int i = 0; i < 10; i++)
	{
		array2->Push_Back(i);
	}
	//获取数据的测试
	for (int i = 0; i < 10; i++)
	{
		cout << array2->getData(i) << endl;
	}
	//设置值的测试
	array2->setData(0, 1000);
	cout << array2->getData(0) << endl;

	//获取数组大小
	cout << "array2的数组大小" << array2->getSize() << endl;

	//获取数组容量
	cout << "array2的数组容量" << array2->getCapacity() << endl;
	
}


int main()
{
	test01();
	system("pause");
	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值