【问题标题】:Overloading function in C++ as unsigned char and unsigned int result in ambiguous将 C++ 中的函数重载为 unsigned char 和 unsigned int 会导致模棱两可
【发布时间】:2015-04-26 15:44:18
【问题描述】:

我必须重载函数:

void wypisz(unsigned int32 x, int n = 1);
void wypisz(unsigned char x, int n = 1);

这是我升起它们的代码:

main()
{
    wypisz((int32)(32), 7);
    wypisz('a', 7);
    return 0;
}

当我尝试使用 G++ 编译它时出现错误:

test.cpp:在函数'int main()'中:

test.cpp:10:21: 错误: 重载 'wypisz(int, int)' 的调用是 暧昧wypisz((int)(32), 7);

test.cpp:10:21: 注意:候选人是:

test.cpp:5:6: 注意:void wypisz(unsigned int, int) void wypisz(unsigned int x, int n = 1);

test.cpp:6:6: 注意:void wypisz(unsigned char, int) void wypisz(unsigned char x, int n = 1);

当我删除 unsigned 时,它会正常编译。

有没有办法调用这个方法——我应该在调用语句中改变什么?不幸的是,我无法更改声明中的任何内容 = 他们必须保持原样。

【问题讨论】:

    标签: g++ overloading


    【解决方案1】:

    问题在于,在您的函数调用中,您正在转换为int32,它既不是unsigned char,也不是unsigned int32。事实上,它可以隐式转换为它们中的任何一个(编译器可以自动转换它)。但是,由于它可以自动将其转换为 either,它不知道将其转换为 哪个,这就是为什么调用不明确的原因。

    要明确调用该方法,只需将其转换为unsigned int32

    wypisz((unsigned int32)32, 7);
    

    现在,编译器不必进行任何隐式转换,因为存在完全匹配。相反,它只是调用正确的函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 2012-05-06
      • 1970-01-01
      • 1970-01-01
      • 2012-04-28
      • 1970-01-01
      相关资源
      最近更新 更多