案例说明
设计一个数组类MyArray,重载[]符号操作,
数组初始化时,对数组的个数进行有效检查
1)index<0 抛出异常eNegtive
2)index=0 抛出异常eZero
3)index>1000 抛出异常eTooBig
4)index<10 抛出异常eTooSmall
4)eSize
类是上述类的基类,实现有参构造,定义virtual void printErr()
输出错误
程序设计
eSize.hpp
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
class eSize
{
public:
virtual void printErr() = 0;
};
class eNegtive: public eSize
{
public:
eNegtive(int index)
{
mIndex = index;
}
public:
void printErr()
{
cout << "eNegtive:" ;
cout << mIndex << endl;
}
private:
int mIndex;
};
class eZero: public eSize
{
public:
eZero(int index)
{
mIndex = index;
}
public:
void printErr()
{
cout << "eZero: " ;
cout << mIndex << endl;
}
private:
int mIndex;
};
class eTooBig : public eSize
{
public:
eTooBig(int index)
{
mIndex = index;
}
public:
void printErr()
{
cout << "eTooBig: " ;
cout << mIndex << endl;
}
private:
int mIndex;
};
class eTooSmall : public eSize
{
public:
eTooSmall(int index)
{
mIndex = index;
}
public:
void printErr()
{
cout << "eTooSmall: " ;
cout << mIndex << endl;
}
private:
int mIndex;
};
MyArray.hpp
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include "eSize.hpp"
class MyArray
{
public:
MyArray();
MyArray(int num);
~MyArray();
public:
//重载[]
int& operator[](int index);
private:
int mLen;
int* mBuf;
};
MyArray::MyArray()
{
mLen = 0;
mBuf = NULL;
throw eZero(mLen);
}
MyArray::MyArray(int num)
{
mLen = num;
if (mLen < 0)
{
throw eNegtive(mLen);
}
if (mLen > 1000)
{
throw eTooBig(mLen);
}
if (0 < mLen < 10)
{
throw eTooSmall(mLen);
}
mBuf = new int[mLen];
}
MyArray::~MyArray()
{
if (mBuf != NULL)
{
delete[] mBuf;
mLen = 0;
}
}
int& MyArray::operator [](int index)
{
return mBuf[index];
}
main.cpp
#include <iostream>
#include "eSize.hpp"
#include "MyArray.hpp"
using namespace std;
void playFunc()
{
try
{
MyArray m(100000);
}
catch (eSize &e) //用基类接实现多态
{
e.printErr();
}
catch ( ... )
{
cout << "其他错误" << endl;
}
}
int main()
{
playFunc();
cout << "hello world!" << endl;
system("pause");
return 0;
}
结论
异常处理机制比传统的错误检查方便,利用多态和异常结合,能够大大的简化代码,该文供以后复习使用
多态实现条件:
1 、有继承
2 、有虚函数重写
3 、有基类指针指向派生类对象
这样在基类指针调用重写的函数时,就会发生多态