C++学习笔记 lesson2 类和对象

本文介绍了一个简单的可变长数组类实现,通过动态调整数组大小来支持数组元素的增删操作,并提供了基本的数据访问和修改功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可变长数组举例

#include<cstringt.h>
//可变长数组
// new delete  更改长度 new新空间 , copy旧空间 , delete旧空间
// malloc free relloc  分配起来更简单
class MyArray
{
public:
 
	MyArray(const  size_t len=10)//给初始长度
	{
		_index = 0;
		_len = len;
		_data = new int[_len];
	}
	~MyArray()
	{
		if (_data)
			delete[]_data;
	}

	int GetData(const size_t index) const
	{
		if (_len > index)
			return _data[index];
		return 0;
	}

	void SetData(const size_t index, const int num)
	{
		if (_len > index)
			_data[index] = num;
	}

	unsigned int GetLen() const //有效的长度 返回_index 
 	{
		return _index;
	}

	void AddData(const int num) //可以把Add和set合并
	{
		if (_index >= _len)
		{
			_len = _index * 2;
			int *temp = new int[_len];//每次分配*2的空间
			memcpy(temp, _data, _index*sizeof(int));
			delete[]_data;
			_data = temp;
			 
		}
		_data[_index++] = num; // index后++ ,否则无_data[0]
	}
	void AddData(const MyArray&data) //增加自身对象
	{
		for (unsigned int i = 0; i < data._index; ++i)
		{
			//const 方法能够被const对象调用, const对象只能调用const方法
			AddData(data.GetData(i));//不能将“this”指针 每一个对象里面的隐藏属性,每一个对象都有
			
			//this 是一个对象的代名词,区分不同的对象
			//每一个类里面,为了区分每一个对象,会默认包含一个this指针
			//
		}
		 
	}
	void AddData(const int *data,const unsigned int ) //增加数组,需要长度参数 
	{
		for (int i = 0; i < _len; i++)
		{
			AddData(data[i]);
		}
	}//写函数的重载时,会相互调用,节约代码量

	/*int& Index( const size_t index) 
	{
		if (index<_len)
		return _data[index];
	} 使用引用直接返回,返回index>len的情况不方便表示*/
private:
	int *_data;
	unsigned int _len;   //已经分配的空间
	unsigned int _index;  //已经使用的空间
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值