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.\n";
            std::cout << "Enter next set of numbers <q to quit>: ";
    }
    std::cout << "Bye!\n";
    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。當然,必須確保其他函數沒有將該全局變量用於其他目的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM