操作员C++的模棱两可的过载

Ambiguous overload for operator C++

本文关键字:模棱两可 操作员 C++      更新时间:2023-10-16
#include <iostream>
using namespace std;
class StringNum {
public:
string s;
StringNum() {s = "";}
public:
StringNum(int n) {
for (int i=1; i<=n; i++) s += "x";
}
operator int () {
return s.length();
}
StringNum operator - (StringNum v) {
int len = s.length() - v.s.length();
StringNum res;
for (int i=1;i<=len;i++) res.s += "x";
return res;
}
/* // long solution. But this will allow the program to run.
template <class T>
StringNum operator - (T value) {
return (*this) - StringNum(value);
}
*/
};
int main()
{
StringNum x(4);
cout << 3 - x; // this compiles
cout << x - 3; // error: ambiguous overload for operator - 
// change the program so that the 2nd line output 2
return 0;
}

所以我有一个可以从 int/downcast 向上转换为 int 的类(这是简化版本,在实际版本中 StringNum 是 HighPrecisionFloat,int 是 int/float/double/.. 等(。

当我编译程序时,错误消息

In function 'int main()':|
error: ambiguous overload for 'operator-' (operand types are 'StringNum' and 'int')|
note: candidate: operator-(int, int) <built-in>|
note: candidate: StringNum StringNum::operator-(StringNum)|

发生这种情况是因为有两种方法可以理解x - 3

a) int(x) - 3
b) x - StringNum(3)

一种方法是为每个运算符使用模板(+,-,*,/,点积等...(但这不是很方便,因为我必须为每个运算符编写模板。

有没有更好的解决方案解决这个问题?我想打电话给x - StringNum(3).谢谢。

你可以将构造函数转换为 intexplicit

编译器不会再在这些类型之间进行隐式转换,但您仍然可以这样使用它们。

auto stringNum = StringNum{3}; //int to StringNum
int y = static_cast<int>(stringNum);