继承和异常

// p15-继承和异常.cpp : 此文件包含 “main” 函数。程序执行将在此处开始并结束。
//
// p15-throw类对象类型异常.cpp : 此文件包含 “main” 函数。程序执行将在此处开始并结束。
//
/*
案例:设计一个数组类容器 Vector,重载[]操作,数组初始化时,对数组的个数进行有效检查
1)index<0 抛出异常errNegativeException
2)index = 0 抛出异常 errZeroException
3)index>1000抛出异常errTooBigException
4)index<10 抛出异常errTooSmallException
5)errSizeException类是以上类的父类,实现有参数构造、并定义virtual void printError()输出错误。
*/
#include
using namespace std;
class errSizeException
{
public:
errSizeException(int size)
{
m_size = size;

}

virtual void printError()
{
	cout << "size:" << m_size << endl;
}

protected:
int m_size;

};

class errNegativeException :public errSizeException
{
public:
errNegativeException(int size) :errSizeException(size)
{

}

virtual void printError()
{
	cout << "errNegativeException size:" << m_size << endl;
}

};

class errTooBigException :public errSizeException
{
public:
errTooBigException(int size) :errSizeException(size)
{

}

virtual void printError()
{
	cout << "errTooBigException  size:" << m_size << endl;
}

};

class errTooSmallException :public errSizeException
{
public:
errTooSmallException(int size) :errSizeException(size)
{

}

virtual void printError()
{
	cout << "errTooSmallException   size:" << m_size << endl;
}

};

class Vector
{
public:
Vector(int size = 128);
int getLength();

int& operator[](int index);
~Vector()
{
	if (m_base) delete[] m_base;
	m_len = 0;
}

private:
int* m_base;
int m_len;
};

Vector::Vector(int len)
{
if (len < 0)
{
throw errNegativeException(len);
}
else if (len==0)
{
throw errSizeException(len);
}
else if (len>1000)
{
throw errTooBigException(len);
}
else if(len<10)
{
throw errTooSmallException(len);
}

m_len = len;
m_base = new int[len];

}

int Vector::getLength()
{
return m_len;
}

int& Vector::operator[](int index)
{
// TODO: 在此处插入 return 语句
return m_base[index];
}

int main()
{
try
{
Vector v(100);
for (int i = 0; i < v.getLength(); i++)
{
v[i] = i + 10;
printf(“v[i]:%d\n”, v[i]);
}
}
catch (errSizeException& err)
{
err.printError();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值