【发布时间】:2014-04-30 18:25:10
【问题描述】:
在 C++ 中,我正在尝试使用函数指针编写函数。如果为不存在的函数传递函数指针,我希望能够抛出异常。我试图像处理普通指针一样处理函数指针并检查它是否为空
#include <cstddef>
#include <iostream>
using namespace std;
int add_1(const int& x) {
return x + 1;
}
int foo(const int& x, int (*funcPtr)(const int& x)) {
if (funcPtr != NULL) {
return funcPtr(x);
} else {
throw "not a valid function pointer";
}
}
int main(int argc, char** argv) {
try {
int x = 5;
cout << "add_1 result is " << add_1(x) << endl;
cout << "foo add_1 result is " << foo(x, add_1) << endl;
cout << "foo add_2 result is " << foo(x, add_2) << endl; //should produce an error
}
catch (const char* strException) {
cerr << "Error: " << strException << endl;
}
catch (...) {
cerr << "We caught an exception of an undetermined type" << endl;
}
return 0;
}
但这似乎不起作用。最好的方法是什么?
【问题讨论】:
-
能贴出调用代码吗?
-
您是否至少通过传递
NULL或nullptr作为函数指针的参数来测试它? -
@RSahu 我已经添加了更多关于如何使用它的代码。
-
@CaptainObvlious 我更关心传递一个不存在的函数而不是传递一个空指针。我只是想弄清楚如何去做。
-
@John,带有
add_2的行如果未声明将导致编译器错误,如果已声明但未定义则会导致链接时错误。
标签: c++ exception pointers exception-handling function-pointers