C++异常what()函数重写

main里面这样:


for(;;){

try{
q_mytype.enQ(MyType());
}catch(exception& e){
cout<<"EXCEPTION!"<<e.what()<<endl;
break;
}

}


Queue.h里面这样:

template<typename T>
void Queue<T>::ensureCapacity(){
T* doubled;
if(size == capacity){ // The queue is full, and the user attempts to insert a new element.
try{
doubled = new T[capacity*2]; // Double the capacity.
}
catch(std::bad_alloc& e){ // When memory is not sufficient, it will throw an exception of bad_alloc.
throw NoSpaceForCapacity(); // Exception propagation.
}


std::cout<<"Capacity is doubled from "<<capacity<<" to "<<capacity*2<<std::endl;
T* old = Elements;
Elements = doubled;
for(int i = 0; i<capacity; i++){
Elements[i] = old[(start+i)%capacity]; // Copy elements from the old queue into the new one. Notice that the start position will be rewound to 0.
}
start = 0 ;
capacity*=2; // Update the information of capacity.
delete [] old;
}else{
return;
}
}


template<typename T>
void Queue<T>::enQ(T t){
ensureCapacity();
Elements[(start+size)%capacity] = t;
size++; // Update size.
return;
}


Exception.h里面这样:

class NoSpaceForCapacity: public std::bad_alloc{ // Memory is not large enough for the capacity of a queue to be doubled.
public:
NoSpaceForCapacity():bad_alloc(){
}
const char* what() const throw(){
return "No space for a doubled capacity!";

};


粗体字如果不写的话,main里面出来的字符串会是std::bad_alloc!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值