#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
*/
重载[],explicit
最新推荐文章于 2024-07-24 17:44:23 发布