gpt4 book ai didi

c++ - 将重载函数分配给函数指针作为默认值

转载 作者:行者123 更新时间:2023-11-30 02:28:14 24 4
gpt4 key购买 nike

一个函数

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)”

我的实际函数是我定义的类的成员函数 exception 命名空间 HMstd

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。

另见:

How do I specify a pointer to an overloaded function?

关于c++ - 将重载函数分配给函数指针作为默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40975945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com