首页 > 解决方案 > const int 和 int& 签名的 C++ 覆盖错误

问题描述

我正在通过 GCC 7.5.0 编译 C++ 程序,但它抱怨不明确的覆盖函数bool ReadRegister(const uint16_t, const uint16_t)bool ReadRegister(const uint16_t, uint16_t &). const uint16_t和是完全不同的uint16_t &数据类型,我错了吗?

标签: c++linuxgcc

解决方案


你的代码是错误的。当你调用readRegister函数时,编译器不知道你在调用哪一个,它会报告'call of overload is ambiguous'错误。

在 C++ 中,引用绑定没有 const 限定转换。直接引用绑定仅在精确匹配时与传递值比较,并派生到基本转换。https: //en.cppreference.com/w/cpp/language 中的更多详细信息/overload_resolution

例如:

void f(int (*)() noexcept); // #1
void f(int (*)()); // #2

void g(int (&)() noexcept); // #3
void g(int (&)()); // #4

#1 的优先级高于 #2,而 #3 和 #4 是相等的。所以记住规则即可。


推荐阅读