【问题标题】:Ambiguous overload for operator C++运算符 C++ 的不明确重载
【发布时间】:2020-02-14 12:09:33
【问题描述】:
#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). 谢谢。

【问题讨论】:

  • 与您的问题无关,但请花点时间阅读Why should I not #include <bits/stdc++.h>?
  • @Someprogrammerdude 我只在单文件程序中这样做:D 所以这应该不是问题。 #include ,使用命名空间std;只用于比赛,不工作
  • 直到我(和其他人)尝试用另一个编译器编译你的程序。为您节省了 10 秒,为试图帮助您的人浪费了时间。
  • 我已经编辑了我的帖子。谢谢。

标签: c++ templates constructor type-conversion operator-overloading


【解决方案1】:

您可以将您的构造函数转换为 int explicit

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

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

【讨论】:

  • 但这消除了执行以下操作的能力:int res = x - 2(没有显式转换的计算)。
  • @HuyĐứcLê 您应该在问题中提及您希望能够做什么。 x-2 仍然可以使用内置的 -
  • @HuyĐứcLê 在此处添加 explicit 主要取决于您真正想要实现的目标,但通常将其添加到单参数构造函数中是一种很好的做法,因为它会禁用可能发生的令人惊讶的转换。
  • 成功了。答案是使构造函数显式。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-09
  • 1970-01-01
  • 1970-01-01
  • 2020-01-09
  • 2020-10-02
相关资源
最近更新 更多