您的位置:首页 > 编程语言 > C语言/C++

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

2016-04-20 23:50 281 查看
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!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: