在C++中,bool函數通常用于返回一個操作是否成功的布爾值
#include<iostream>
#include <stdexcept>
bool divide(int a, int b, int &result) {
if (b == 0) {
throw std::runtime_error("Division by zero");
}
result = a / b;
return true;
}
int main() {
try {
int result;
divide(10, 0, result);
std::cout << "Result: "<< result<< std::endl;
} catch (const std::runtime_error &e) {
std::cerr << "Error: " << e.what()<< std::endl;
}
return 0;
}
#include<iostream>
enum ErrorCode {
SUCCESS,
DIVISION_BY_ZERO
};
ErrorCode divide(int a, int b, int &result) {
if (b == 0) {
return DIVISION_BY_ZERO;
}
result = a / b;
return SUCCESS;
}
int main() {
int result;
ErrorCode error = divide(10, 0, result);
if (error == SUCCESS) {
std::cout << "Result: "<< result<< std::endl;
} else if (error == DIVISION_BY_ZERO) {
std::cerr << "Error: Division by zero"<< std::endl;
}
return 0;
}
#include<iostream>
#include<optional>
std::optional<int> divide(int a, int b) {
if (b == 0) {
return std::nullopt;
}
return a / b;
}
int main() {
auto result = divide(10, 0);
if (result) {
std::cout << "Result: " << *result<< std::endl;
} else {
std::cerr << "Error: Division by zero"<< std::endl;
}
return 0;
}
這些方法都可以有效地處理bool函數中的錯誤。選擇哪種方法取決于你的需求和編程風格。