我想實現二叉搜索樹。我有私人和公共get()方法。對於private get(),我返回Node對象,或者如果找不到該節點,則返回異常。對於public get()我返回Node對象的值,即std :: string或捕獲該異常。用戶只能調用public get(),我試圖避免讓用戶使用異常。這就是爲什麼我在public get()中捕獲異常而不是將其重新推送給用戶的原因。我的問題是,當public get()捕獲異常時如何終止函數,因爲我的返回類型是std :: string。我試圖返回-1或std :: terminate(),但他們沒有工作。有沒有辦法處理這個問題,或者我必須重新拋出異常或更改我的返回類型?謝謝。這是我的代碼。發生異常時如何返回非void函數,而不使用異常? C++
// public
std::string BST::get(int key) {
Node *node;
try {
node = get(key, my_root);
}
catch (const std::out_of_range& oor) {
std::cout << oor.what() << std::endl;
// How to let the function terminate here?
}
return node->value;
}
//private
Node* BST::get(int key, Node* root) {
if (root == NULL) {
throw std::out_of_range("Cannot find.");
}
if (key < root->key) {
return get_node(key, root->left);
} else if (key > root->key) {
return get_node(key, root->right);
} else {
return root;
}
}
您可以決定如何表示「該項目不存在」。例如,您可以使用空字符串。 –
或者,表示可空對象的一種方法是使用指針,但如果你走這條路線,則必須更加註意內存管理。 – huu
這聽起來像是你問到如何在函數結束之前「離開」一個函數。那是對的嗎? –