在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函数中的错误。选择哪种方法取决于你的需求和编程风格。