案例:设计一个数组类 MyArray,重载[]操作,
数组初始化时,对数组的个数进行有效检查
1)size<0 抛出异常eNegative
2)size= 0 抛出异常 eZero
3)size>1000抛出异常eTooBig
4)size<10 抛出异常eTooSmall
5)eSize类是以上类的父类,实现有参数构造、并定义virtual void printErr()输出错误。
#pragma warning(disable : 4996)
#include <iostream>
using namespace std;
class eSize
{
public:
eSize(int size)
{
this->m_size = size;
}
virtual void PrintErr() = 0;
protected:
int m_size;
};
class eNegative :public eSize
{
public:
eNegative(int size) :eSize(size)
{
;
}
virtual void PrintErr()
{
printf("抛出异常eNegative,size:%d", m_size);
}
};
class eZero :public eSize
{
public:
eZero(int size) :eSize(size)
{
;
}
virtual void PrintErr()
{
printf("抛出异常eZero,size:%d", m_size);
}
};
class eTooBig :public eSize
{
public:
eTooBig(int size) :eSize(size)
{
;
}
virtual void PrintErr()
{
printf("抛出异常eTooBig,size:%d", m_size);
}
};
class eTooSmall :public eSize
{
public:
eTooSmall(int size) :eSize(size)
{
;
}
virtual void PrintErr()
{
printf("抛出异常eTooSmall,size:%d", m_size);
}
};
class MyArray
{
public:
MyArray(int len);
int & operator[](int index);
~MyArray();
int GetLen();
private:
int *m_place;
int m_len;
};
MyArray::MyArray(int len)
{
if (len < 0)
{
throw eNegative(len);
}
else if(len == 0)
{
throw eZero(len);
}
else if (len >100)
{
throw eTooBig(len);
}
else if (len < 3)
{
throw eTooSmall(len);
}
m_len = len;
m_place = new int[len];
}
MyArray::~MyArray()
{
if (m_place != NULL)
{
delete[] m_place;
m_place = NULL;
m_len = 0;
}
}
int & MyArray::operator[](int index)
{
return m_place[index];
}
int MyArray::GetLen()
{
return m_len;
}
int main()
{
try
{
MyArray a(120);
for (int i = 0; i < a.GetLen(); i++)
{
a[i] = i + 1;
printf("%d ", a[i]);
}
}
catch (eSize &e)
{
e.PrintErr();
}
system("pause");
return 0;
}