C++练习(一)—案例(一)

数组类的封装

Myarray.h
#pragma once
#include<iostream>

using namespace std;

class My_Array
{
public:
	//  默认构造函数
	My_Array();

	//  有参构造函数
	My_Array(int capacity);

	//  拷贝构造函数
	My_Array(const My_Array & arr);

	//  尾插
	void PushBack(int val);

	//  根据位置设置元素
	void setData(int index, int val);

	//  根据位置获取元素
	int getData(int index);

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

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

	//  析构函数
	~My_Array();


private:
	//	指向堆区的地址
	int *pAdress;

	//  数组容量
	int m_Capacity;

	//	数组大小
	int m_Size;
};

Myarray.cpp
#include "Myarray.h"

My_Array::My_Array()
{
	//	cout << "默认构造函数调用" << endl;
	this->m_Capacity = 100;
	this->m_Size = 0;
	this->pAdress = new int[this->m_Capacity];
}

My_Array::My_Array(int capacity)
{
	//	cout << "有参构造函数调用" << endl;
	this->m_Capacity = capacity;
	this->m_Size = 0;
	this->pAdress = new int[this->m_Capacity];
}

My_Array::My_Array(const My_Array & arr)
{
	//	cout << "拷贝构造函数调用" << endl;
	this->m_Size = arr.m_Size;
	this->m_Capacity = arr.m_Capacity;

	this->pAdress = new int[this->m_Capacity];

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

void My_Array::PushBack(int val)
{
	this->pAdress[this->m_Size] = val;
	this->m_Size++;
}

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

int My_Array::getData(int index)
{
	return this->pAdress[index];
}

int My_Array::getSize()
{
	return this->m_Size;
}

int My_Array::getCapacity()
{
	return this->m_Capacity;
}

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

1.cpp
#include<iostream>

using namespace std;

#include "Myarray.h"

void test01()
{
	My_Array *arr = new My_Array(10);
	delete arr;

	My_Array arr2;

	for (int i = 0; i < 10; i++)
	{
		arr2.PushBack(i + 100);
	}
	
	
	My_Array arr3(arr2);

	for (int i = 0; i < 10; i++)
	{
		cout << "位置为" << i + 1 << "的元素为" << arr3.getData(i) << endl;
	}

	cout << "数组的容量为" << arr3.getCapacity() << endl;
}


int main()
{
	test01();
	system("pause");
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

walkerrev_ll

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值