16.定义一维数组类Array,成员数组使用动态内存。重载自增和自减运算符(前置、后置)实现数组元.

该博客详细介绍了如何在C++中定义一个一维数组类,包括动态内存分配,重载前置和后置自增、自减运算符。通过一个具体的测试案例展示了类的使用,输出了数组元素自增和自减后的结果。此外,还实现了拷贝构造函数、赋值运算符和析构函数,确保了内存管理的正确性。

16.定义一维数组类Array,成员数组使用动态内存。重载自增和自减运算符(前置、后置)实现数组元
素的自增和自减。具体要求如下:(1)私有数据成员:int *p; //int n; //一维数组的大小
(2)公有成员函数:
构造函数:初始化数据成员;拷贝构造函数
重载前置自增的成员函数; 重载后置自增的成员函数; 重载前置自减的友元函数; 重载后置自减的友元函数:
void print():输出数组成员的函数;    析构函数:释放动态内存;
若有必要可增加其它成员函数。
(3)以数组“{1,2,3,4,5,6,7}”对所定义的类进行测试,要求输出数组元素的自增和自减(前置、后置)情况。

#include<iostream>
using namespace std;
class Array
{
protected:
	int* p;
	int n;
public:
	Array()
	{
		p = 0;
		n = 0;
	}
	Array(int* parr, int n)
	{
		this->n = n;
		p = new int[n];
		for (int i = 0; i < this->n; i++)
		{
			p[i] = parr[i];
		}
	}
	Array(Array & a)
	{
		this->n = a.n;
		p = new int[this->n];
		for (int i = 0; i < this->n; i++)
		{
			p[i] = a.p[i];
		}
	}
	/*重载前置自增的成员函数;重载后置自增的成员函数;重载前置自减的友元函数;重载后置自减的友元函数:
voidprint():输出数组成员的函数;析构函数:释放动态内存;*/
	Array operator++()
	{
		for (int i = 0; i < this->n; i++)
		{
			this->p[i]++;
		}
		return *this;
	}
	Array operator++(int)
	{
		Array a = *this;
		for (int i = 0; i < this->n; i++)
		{
			this->p[i]++;
		}
		return a;
	}
	friend Array operator--(Array & a1)
	{
		for (int i = 0; i < a1.n; i++)
		{
			a1.p[i]--;
		}
		return a1;
	}
	friend Array operator--(Array & a1, int)
	{
		Array a2 = a1;
		for (int i = 0; i < a1.n; i++)
		{
			a1.p[i]--;
		}
		return a2;
	}
	void operator=(const Array& a)
	{
		if (this->p)
			delete[]this->p;
		if (a.p)
		{
			this->n = a.n;
			this->p = new int[this->n];
			for (int i = 0; i < this->n; i++)
			{
				this->p[i] = a.p[i];
			}
		}
		else
			p = 0;
	}
	void print()
	{
		for (int i = 0; i < this->n; i++)
			cout << p[i] << "\t";
		cout << endl;
	}
	~Array()
	{
		if (p)
			delete[]p;
	}
};
int main()
{
	int arr[7] = { 1,2,3,4,5,6,7 };
	Array a(arr, 7); a.print();
	cout << "**********************" << endl;
	Array b, c, d,e;
	b = a++; b.print();
	cout << "_______" << endl;
	c = ++a; c.print();
	cout << "_______" << endl;
	d = a--;d.print();
	cout << "_______" << endl;
	e = --a; e.print();
	cout << "_______" << endl;
	system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值