【问题标题】:An error "Call to constructor of ' ' is ambiguous", although the class's constructor parameters do not look the same?错误“调用''的构造函数不明确”,尽管类的构造函数参数看起来不一样?
【发布时间】:2020-11-25 04:56:48
【问题描述】:

出现Call to constructor of 'Binary' is ambiguous 的错误消息,该错误消息仅在macOS 上使用LLVM 编译器时出现,但在Windows 上不会出现。
此外,类的构造函数参数看起来也不一样。

class Binary {
public:
    Binary() = default;
    Binary(uintmax_t containerSize);
    Binary(unsigned char binary);
    Binary(std::initializer_list<unsigned char> binaryList);
    // .....
};

// When using
// fileSize is `std::streamoff` data type
Binary fileContent((unsigned long long)fileSize)  // << This line is causing the problem.

我的班级出了什么问题?

【问题讨论】:

  • 如果意图是调用第二个 ctor,为什么要转换为 unsigned long long 而不是 uintmax_t ?我敢打赌,它们在您的 Windows 版本上是相同的类型根,但在您的 MacOS 版本上是不同的。
  • uintmax_tunsigned long long,所以我认为unsigned long long 是合适的,而且我在 macOS 和 windows 上做了同样的事情,但 windows 没有出现该消息。
  • 是的,我们明白了;你在你的帖子里说了这么多。现在再读一遍我说的话,具体来说,不同平台上的uintmax_t不一定必然与unsigned long long同义,所以你的第一句话uintmax_tunsigned long long不是普遍准确的。

标签: c++ class compiler-errors


【解决方案1】:

uintmax_t 是您机器上最大宽度无符号整数类型的 typedef。编译代码时,如果该类型不是完全 unsigned long long,那么这个调用:

Binary fileContent((unsigned long long)fileSize); 

是模棱两可的,因为参数需要经过一次转换才能匹配这些构造函数之一:

Binary(uintmax_t containerSize); // conversion from unsigned long long to uintmax_t needed
Binary(unsigned char binary);    // conversion from unsigned long long to unsigned char needed

编译器无法在它们之间进行选择,出现错误。

如果uintmax_t 恰好是完全 unsigned long long,那么第一个构造函数是完全匹配的,并且被选中,程序编译。想必这就是你看到的 macOS 和 Windows 编译器版本之间的区别。

【讨论】:

  • 对不起,uintmax_tunsigned char 有什么相似之处让编译器认为两者相同?
  • 不,uintmax_tunsigned char 之间没有相似之处。事实上,它们都与unsigned long long 相同,这也是编译器无法选择的原因。编辑了答案,希望对您有所帮助。
  • 我发现uintmax_t是这样声明的typedef long unsigned int uintmax_ttypedef long long unsigned int uintmax_t
  • 是的,第一个需要转换,第二个是完全匹配。
猜你喜欢
  • 1970-01-01
  • 2021-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-28
  • 1970-01-01
  • 2018-02-28
相关资源
最近更新 更多