当我在写关于基本运算符重载一些代码。我来到这个代码片段,ISO C++说,这些都是不明确的,操作符重载
struct MyInt {
public:
MyInt() : data() { };
MyInt(int val) : data(val) { }
MyInt& operator++() {
++data;
return (*this);
}
MyInt operator++(int) {
MyInt copy = *this;
++data;
return copy;
}
MyInt& operator+=(const MyInt& rhs) {
data += rhs.data;
return *this;
}
MyInt operator+(const MyInt& rhs) const {
MyInt copy = *this;
copy += rhs;
return copy;
}
int data;
};
这些都是正常,直到我的类
MyInt operator+(const MyInt& lhs, const MyInt& rhs)
{
MyInt copy = lhs;
copy.data += rhs.data;
return copy;
}
的声明之后加入这个权利有了这个主declartion
int main() {
MyInt mi = 10;
MyInt mi2 = 11;
MyInt mi3 = mi++ + ++mi2;
mi3 += mi2;
}
当我尝试编制,G ++我
warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:
MyInt mi3 = mi++ + ++mi2;
^
note: candidate 1: MyInt operator+(const MyInt&, const MyInt&)
MyInt operator+(const MyInt& lhs, const MyInt& rhs)
^
note: candidate 2: MyInt MyInt::operator+(const MyInt&) const
MyInt operator+(const MyInt& rhs) const {
抛出此警告
从我见过的其他问题来看,它们都是错误而不是警告。所以我不确定为什么它的代码仍然有效。希望有人能向我解释为什么会发生这种情况。
在此先感谢。
@Drop这是什么UB? 'MyInt mi3 = mi ++ + ++ mi2;'是三个不同的变量,所以没有UB。 – NathanOliver
这里没有真正的问题。 “他们为什么不明确?” “为什么g ++将此作为警告并仍然创建二进制文件?” –
@NathanOliver我认为这是因为左边的后缀意味着'const&'被转换为一个临时值......但这似乎排除了lhs + rhs定义是一个合格的重载,所以我'我不确定除了“ISO是这么说的”之外,还有什么是“模棱两可的”。 [另外,我上面的评论回复了一个现在被删除的评论,称这是一个值得采访的UB例子] –