zoukankan      html  css  js  c++  java
  • C++异常 返回错误码

    一种比异常终止更灵活的方法是,使用函数的返回值来指出问题。例如,ostream类的get(void)成员ASCII码,但到达文件尾时,将返回特殊值EOF。对hmean()来说,这种方法不管用。任何树脂都是有效的返回值,因此不存在可用于指出问题的特殊值。在这种情况下,可使用指针参数或引用参数来将值返回给调用能够程序,并使用函数的返回值来指出成功还是失败。istream族重载>>运算符使用了这种技术的变体。通过告知调用程序是成功了还是失败了,使得程序可以采取异常终止程序之外的其他措施。下面的程序是一个采用这种方式的示例,它将hmean()的返回值重新定义为bool,让返回值指出成功了还是失败了,另外还给该函数增加了第三个参数,用于提供答案。
    error2.cpp

    // error2.cpp -- returning an error code
    #include <iostream>
    #include <cfloat>   // (or float.h) for DBL_MAX
    
    bool hmean(double a, double b, double * ans);
    
    int main()
    {
        double x, y, z;
    
        std::cout << "Enter two numbers: ";
        while (std::cin >> x >> y)
        {
            if (hmean(x, y, &z))
                std::cout << "Harmonic mean of " << x << " and " << y
                        << " is " << z << std::endl;
            else
                std::cout << "One value should not be the negative "
                          << "of the other - try again.
    ";
                std::cout << "Enter next set of numbers <q to quit>: ";
        }
        std::cout << "Bye!
    ";
        return 0;
    }
    
    bool hmean(double a, double b, double * ans)
    {
        if (a == -b)
        {
            *ans = DBL_MAX;
            return false;
        }
        else
        {
            *ans = 2.0 * a * b / (a + b);
            return true;
        }
    }

    效果:

    Enter two numbers: 3 6
    Harmonic mean of 3 and 6 is 4
    Enter next set of numbers <q to quit>: 10 -10
    One value should not be the negative of the other - try again.
    Enter next set of numbers <q to quit>: 1 19
    Harmonic mean of 1 and 19 is 1.9
    Enter next set of numbers <q to quit>: q
    Bye!

    另一种在某个地方存储返回条件的方法是使用一个全局变量。可能问题的函数可以在出现问题时将该全局变量设置为特定的值,而调用程序可以检查该变量。传统的C语言数学库使用的就是这种方法,它使用的全局变量名为errno。当然,必须确保其他函数没有将该全局变量用于其他目的。

  • 相关阅读:
    java的装箱和拆箱详解
    java语法基础
    java变量与内存深入了解
    java的配置环境简介
    Python脚本--利用运算符重载简化MongoDB的命令
    Python多线程编程,线程锁
    Python多进程,同步互斥,信号量,锁补充上一篇文章
    Python多进程编程及多进程间的通信,数据传输
    Jmeter深度学习第一天——简单请求、带header请求、返回值乱码问题
    JAVA Spring工程一些配置问题的解决
  • 原文地址:https://www.cnblogs.com/moonlightpoet/p/5670343.html
Copyright © 2011-2022 走看看