操作员C++的模棱两可的过载
Ambiguous overload for operator C++
#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);
相关文章:
- <<操作员在下面的行中工作
- "Inverse SFINAE"避免模棱两可的过载
- C++ 与操作员不匹配<<
- 操作员C++的模棱两可的过载
- 模棱两可的重载模板
- C++中>>操作员过载时出现问题?
- NaN 上的宇宙飞船操作员
- 调用重载的"<大括号括起来的初始值设定项列表>"对于对来说就足够了是模棱两可的
- 比根<操作员
- 模棱两可的 != reverse_iterator运算符
- SFINAE不能防止模棱两可的操作员过载吗?
- 什么是现实中的"endl"(或任何输出操纵器)?它是如何实现的,它如何与操作员<<一起工
- VSCode 说 std::chrono 是模棱两可的,如果运算符<<重载
- 为什么对模板的调用不模棱两可?
- 模棱两可的过载 对于操作员"<<"
- 操作员的模棱两可的过载C =
- 超载运算符*与操作员双重模棱两可()
- 操作员的过载模棱两可>>
- C :操作员过载:课堂上和班级.歧义前操作员的模棱两可
- 操作员的模棱两可的过载