一种比异常终止更灵活的方法是,使用函数的返回值来指出问题。例如,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 ;
} 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。当然,必须确保其他函数没有将该全局变量用于其他目的。