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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ndfeixia/article/details/51205043

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!

展开阅读全文

没有更多推荐了,返回首页