温馨提示×

C++ bool函数的错误处理方法

c++
小樊
83
2024-09-04 20:20:14
栏目: 编程语言

在C++中,bool函数通常用于返回一个操作是否成功的布尔值

  1. 使用异常处理:
#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;
}
  1. 使用错误码:
#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;
}
  1. 使用std::optional或std::pair:
#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函数中的错误。选择哪种方法取决于你的需求和编程风格。

0