重载[],explicit

#include <iostream>
using namespace std;

//数组类
typedef int T;
class Array
{
	T* data;  //指向堆中的数据
	int sz;  //表示数据的个数
	int max;  //堆中的空间大小
	//扩容
	void expand()
	{
		max = 2 * max;
		T* t = new T[max];
		for(int i = 0; i < sz; i++)
		{
			t[i] = data[i];
		}
		delete[] data;
		data = t;
	}
public:
	//构造函数不允许隐式调用
	explicit Array(int n = 5):max(n),sz(0)
	{
		data = new T[n];
	}
	
	~Array()
	{
		delete[] data;
	}
	
	Array(const Array& a)
	{
		max = a.max;
		sz = a.sz;
		data = new T[max];
		for(int i = 0; i < sz; i++)
		{
			data[i] = a.data[i];
		}
	}

	Array& operator=(const Array& a)
	{
		if(this == &a) return *this;
		delete[] data;
		data = new T[a.max];
		max = a.max;
		sz = a.sz;
		for(int i = 0; i < sz; i++)
		{
			data[i] = a.data[i];
		}
	}

	bool insert(int index,const T& d)
	{
		if(index < 0 || index > sz) return false;
		if(sz == max) expand();
		//sz,表示数据的个数,max表示堆中空间的大小
		for(int i = sz; i > index; i--)
		{
			data[i] = data[i-1];
		}
		data[index] = d;
		sz++;
		return true;
	}
	
	bool push_back(const T& d)
	{
		return insert(sz,d);
	}

	friend ostream& operator<<(ostream& o,const Array& a)
	{
		for(int i = 0; i < a.sz; i++)
		{
			o << a.data[i] << ' ';
		}
		return o;
	}

	T& operator[] (int index)
	{
		return data[index];
	}
	
	//这个函数暂时不知道是做嘛的……
	T& at(int index)
	{
		if(index < 0 || index >= sz) 
			 throw"out";
		return data[index];
	}

	T& operator[](char c)
	{
		return data[c-'a'];
	}

	T& operator[](double d)
	{
		return data[(int)(d+0.5)];
	}

	int size()
	{
		return sz;
	}
};

int main()
{
	Array a;
	a.insert(0,1);
	a.insert(1,2);
	a.push_back(3);
	cout << a << endl;
	Array b = a;
	Array c;
	c = a;
	a[0] = 100;
	a[1] = 200;
	for(int i = 0;i < a.size() ; i++)
	{
		cout << a[i] << ' ';

	}
	cout << endl;
	a['a'] = 123;
	a['b'] = 456;
	a['c'] = 780;
	cout << a << endl;
	a[2.13] = 213;
	a[0.8] = 8;
	a[0.2] = 2;
	cout << a << endl;
}
/*  程序运行结果
1 2 3 
100 200 3 
123 456 780 
2 8 213 
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值