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

标签 c++ function pointers function-pointers default-parameters

对于一个函数

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。

另请参阅:

How do I specify a pointer to an overloaded function?

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

相关文章:

c - 释放指针内存以及指针本身

c++ - 为什么不能像指针一样返回 const 引用?

python - 非本地与静态相同吗?

c++ - Visual Studio (2015) fpermissive 等效标志

c++ - Coin Change 自底向上动态规划

c++ - 为什么派生模板类不能访问基模板类的标识符?

matlab - 矩阵作为函数的输出

c - 用向右移动 'k' 次的单词替换文本中的每个单词

c# - 为什么局部函数并不总是隐藏在 C#7 中?

为 cout 取消引用指针时的 C++ SegFault