1.C++异常处理(二)

2015-07-20 17:44:43 · 作者: · 浏览: 13

\

6.模板类的异常

#include

usingnamespacestd;

//typename会明确类型

//模板的异常,处理通用的数据类型,类中包含一个如果使用

//虚函数,虚函数可以指针,引用来实现

//异常处理机制,一个接口处理通用的异常

template

classArray

{

public:

classwrong

{

public:

//虚函数

virtualvoidshow()

{

cout <<" wrong " <

}

};

classbig :publicwrong

{

public:

intx;

big(intn) :x(n){}

voidshow()

{

cout <<"big wrong"<

}

};

classsmall :publicwrong

{

public:

intx;

small(intn) :x(n){}

voidshow()

{

cout <<"small wrong" <

}

};

Array(intn)

{

if (n > 0 && n<10)

{

throwsmall(n);

}

elseif (n>10000)

{

throwbig(n);

}

elseif (n < 0)

{

throwwrong();

}

else

{

p =newT[n];

size =n;

}

}

private:

intsize;

T *p;

};

voidmain()

{

try

{

Array may(1);

}

catch (Array ::wrong & wrong1)

{

wrong1.show();

}

cin.get();

}

运行结果:

\