对于一个函数
foo( int (*fnptr)(int) );
我想为函数指针设置一个默认值int bar(int)
即指针的默认值为bar
bar
也被重载为
double bar (double);
bool bar (bool);
如何分配值?
我试过了
foo ( int (*fnptr)(int) = bar);
但它不起作用。
编辑我正在使用 MS Visual Studio 并收到错误代码 C2440
“默认参数”:无法从“重载函数”转换为“Error_C (__cdecl *)(HMstd::exception)”
我的实际函数是我定义的命名空间HMstd
的类的成员函数Exception
virtual Error_C execute_protocol(Error_C(*execute)(exception ex) = HMstd::MErr);
函数是
Error_C MErr(Error_C code);
Error_C MErr(char* desc);
Error_C MErr(exception ex);
其中 Error_C
是另一个类
这三个重载函数HMstd::MErr
的定义是
Error_C HMstd::MErr(Error_C code)
{
std::cout << "\n\nError: An Error Of Code " << int(code) << " Occured....\n\n";
return SUCCESS;
}
Error_C HMstd::MErr(char* desc)
{
if (desc == NULLPTR)
return E_NULLPTR;
std::cout << desc;
return SUCCESS;
}
Error_C HMstd::MErr(exception ex)
{
bool Nullar = TRUE;
bool uninit;
for (int i = 0;i < 200;i++)
if (ex.description[i] != '\0')
Nullar = FALSE;
uninit = (int(ex.code) == -201) && Nullar;
if (uninit)
{
return UNINIT_PARAMETER;
}
MErr(ex.code);
MErr(ex.description);
return SUCCESS;
}
最佳答案
快速回答:
使用类型转换
简短代码:
// ...
int bar (int) {
cout << "Right\n";
// bar(true); // just in case you want to invoke bool bar(bool)
// bar(0.0f);
return 0;
}
// ...
int foo (int (*ptr) (int) = static_cast<int (*) (int)>(bar)) {
return ptr(0);
}
// ...
完整代码:
#include <iostream>
using namespace std;
int bar (int) {
cout << "Right\n";
// bar(true); // just in case you want to invoke bool bar(bool)
// bar(0.0f);
return 0;
}
bool bar (bool) {
return false;
}
double bar (double) {
return 0;
}
int foo (int (*ptr) (int) = static_cast<int (*) (int)>(bar)) {
return ptr(0);
}
int main () {
return foo();
}
说明:
您有多个bar
所以我不能输入 = bar
作为默认参数。因此,您必须指定哪个 bar
。我使用了类型转换,因此编译器可以指定其中之一 bar
。我看到你只提供了两个 bar
( bool bar(bool)
和 double bar(double)
,但您不能将这些函数中的任何一个转换为 int bar(int)
(如果 gcc 允许,程序可能无法正常工作,特别是使用 double bar(double)
),因此您需要在新 int bar(int)
注意:
您还可以使用不安全 C 风格类型转换 (int (*)(int)) bar
而不是static_cast<int (*) (int)>(bar)
但这是C++
如果您使用 Turbo C++,上面的代码可能无法运行,因此您可能更喜欢 C 风格的类型转换,或者直接切换到 GCC。
另请参阅:
关于c++ - 将重载函数分配给函数指针作为默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40975945/