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!