c++ - 运算符 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).
谢谢。
解决方案
您可以将构造函数转换为 int explicit
。
编译器不会再在这些类型之间进行隐式转换,但您仍然可以像这样使用它们。
auto stringNum = StringNum{3}; //int to StringNum
int y = static_cast<int>(stringNum);
推荐阅读
- firebase - React Native - 当所有组件都在其中渲染时如何隐藏启动画面?
- python - 当我在表格视图中单击文件时,文件内容未显示
- c# - sqlQuery 与 if else
- css - 是否可以在关闭时更改转换速度?
- docker - 使用resin.io部署时如何更新node-red/node-red-docker镜像中的settings.js?
- c++ - basic_string 的前导/尾随空格不敏感特征
- javascript - 无法让简单的 Javascript 在 Firefox 中工作
- java - 如何在春季将整个表添加到缓存中
- microsoft-graph-api - Microsoft Graph API 邮件加密
- algorithm - C中的抢占式任务调度