我正在尝试编写一个函数模板,它从标准输入接收一个数字作为参数并对其执行平方根运算,除非它恰好是负数,在这种情况下将引发异常。主程序如下所示:
#include "Sqrt _of_Zero_Exception.h"
#include <iostream>
#include <cmath>
using namespace std;
template <typename T>
const T& sqrtNumber(T&);
int main()
{
int a, result;
cout << "Enter number to square root: ";
while (cin >> a){
try{
result = sqrtNumber(a);
cout << "The square root of " << a << " is " << result << endl;
} //end try
catch (SqrtofZeroException &sqrtEx){
cerr << "An exception occurred: " << sqrtEx.what() << endl;
} //end catch
}
return 0;
}
template <typename T>
const T& sqrtNumber(T& num)
{
if (num < 0)
throw SqrtofZeroException();
return sqrt(num);
}
这是头文件:
#include <stdexcept>
//SqrtofZeroException objects are thrown by functions that detect attempts to square root negative numbers
class SqrtofZeroException : public std::runtime_error
{
public:
SqrtofZeroException() //constructor specifies default error message
: runtime_error("square root on a negative number is not allowed"){}
}; //end class SqrtofZeroException
该程序可以在 Visual Studio 上编译,但是<cmath> sqrt
当我尝试在我的sqrtNumber
函数中调用它时,该函数显示为灰色:
当我运行程序时输出是错误的:
如果我将函数模板更改为接受整数参数的普通函数,我可以sqrt
毫无问题地调用。那么这种行为的具体原因是什么?我的函数模板的语法有问题吗?