C++下标访问运算符重载

  1. 定义容器类DoubleArray;
  2. 用来容纳一个double数据序列,可以任意指定下标的范围,而且还要检查下标是否越界;
  3. 为了能像一般数组那样用下标访问其中的元素,需要为DoubleArray重载的下标访问运算符“[]”。
#include 
using namespace std;
class DoubleArray //double数据列
{
private:
	int size; //数据列大小
	double *buf; //数据指针
public:
	DoubleArray(int n); //构造函数
	~DoubleArray()  //析构函数
	{
		delete[]buf;
	}
	double &operator[](int n);  //下标运算符重载
	void show()
	{
		cout << "double数据列为:" << endl;
		for (int j = 0; j < size; j++)
		{
			cout << buf[j]<<endl;
		}
	}
};
DoubleArray::DoubleArray(int n)  //定义构造函数
{
	size = n;
	buf = new double[size + 1];
}
double &DoubleArray::operator[](int n) //定义下标构造函数
{
	static double ch = 0;
	if (n > size || n < 0)  //检查数组是否越界
	{
		cout << "out of the bound" << endl;
		return ch;
	}
	return *(buf+n);
}
int main()
{
	DoubleArray a(4);
	for (int i = 0; i < 4; i++)
	{
		a[i] = 1.4 + i; //赋值
	}
	a.show();
	a[2] = 5.88; //通过下标访问double数据列元素
	a.show();
	system("pause");
	return 0;
}

你可能感兴趣的:(c++下标运算符重载)