我在使用以前在 Android NDK 版本 r8e (GCC) 下编译的一些旧继承代码时遇到此错误。我正在尝试升级以使用 Android NDK 版本 r16 (Clang) 进行编译。我从大学毕业后很多年就没有使用过 C++,但我对编程并不陌生。
方法签名看起来与 header 一致,我看不到任何其他可能导致歧义的运算符签名。当参数显然是 int
时,我不确定为什么它会模棱两可。这个错误的原因是什么?
注释掉其中一个运算符可以解决问题,但两个运算符都是必需的。
标题:
class XmlNode
{
public:
// ... - let me know if you think I might have snipped anything important
XmlNode &operator[](int idx) const;
XmlNode &operator[](const String &name);
// ...
};
class XmlDoc : public XmlNode
{
public:
// snipped ... no further overrides here
};
类:
// ...
XmlNode &operator[](int idx) const
{
return *list[idx];
}
XmlNode &operator[](const String &name)
{
// ...
if(found)
{
// ...
return *list[IndexOf(head)];
}
// not found - create new entry
return Add(name); // add the whole path
}
上下文中的代码:
// ...
int idx = xml.IndexOf("METHOD");
// ...
MyClient::setSaveTrace(xml[idx][0].GetTextAsInt("SaveTrace", TRUE));
错误:
C:/.../myclass.cpp:3392:41: error: use of overloaded operator '[]' is ambiguous (with operand types 'KIT::XmlDoc' and 'int')
MyClient::setSaveTrace(xml[idx][0].GetTextAsInt("SaveTrace", TRUE));
~~~^~~~
C:/.../KIT-Xml.h:94:14: note: candidate function
XmlNode &operator[](int idx) const;
^
C:/.../KIT-Xml.h:95:11: note: candidate function
XmlNode &operator[](const String &name);
^
最佳答案
从这里开始:
class XmlNode
{
public:
// ... - let me know if you think I might have snipped anything important
XmlNode &operator[](int idx) const;
XmlNode &operator[](const String &name);
// ...
};
有两种运算符:一种是const
,另一种是非const
。
对于:
XmlDoc xml;
int idx;
xml[idx];
这是不明确的,因为编译器显然无法决定应用哪个隐式转换。
或者:
((const XmlDoc&)xml).operator[](idx) // for the first
或:
xml.operator[](String::fromInt(idx)) // for the second
备注:
Paul McKenzy 建议可能存在从 String
到 int
的隐式转换导致了这个问题。写下这些时,我得出的结论一定是相反的——存在从 int
到 String
的隐式转换。不知道更好,我只是称它为 String::fromInt(int)
(但它也可能是 String::String(int)
或其他任何东西)。
为了解决歧义,我首先建议显式const
-cast:
((const XmlNode&)xml)[idx]
但这还不够。 (我不确定 this 是否是所使用的特定编译器的弱点。)可能,编译器仍然应用从 const XmlNode&
到 的隐式转换XmlDoc&
并因此识别出同样的歧义。 (这只是猜测。)因此,我的新建议:
((const XmlDoc&)xml[idx]
这带来了进步。 (歧义移至第二个 operator[]
。)
因此,问题的完整解决方案:
((const XmlNode&)((const XmlDoc&)xml)[idx])[0]
提问者报告成功。
我不得不承认,我无法判断这种行为是否符合(哪个)C++ 标准。
关于android - 错误 : use of overloaded operator '[]' is ambiguous,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47667275/