“运算符"的C ++模棱两可的重载 [英] C++ ambiguous overload for ‘operator ’

查看:90
本文介绍了“运算符"的C ++模棱两可的重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里读了几篇关于这种错误的文章,但是我无法解决这个问题. 我很快定义了运算符int和函数f,无法编译. 由于无法解决问题,我进行了几项测试. 谢谢

I'v read several posts here about this kind of errors, but I wasn't able to solve this one... Has soon I define the operator int and the function f, fails to compile. I tested several things by I wasn't able to solve the issue.... Thanks

ex1.cpp: In function ‘int main(int, char**)’:
ex1.cpp:35:13: error: ambiguous overload for ‘operator+’ in ‘a + 4’
ex1.cpp:35:13: note: candidates are:
ex1.cpp:35:13: note: operator+(int, int) <built-in>
In file included from ex1.cpp:3:0:
Fraccao.h:41:9: note: Fraccao operator+(const Fraccao&, const Fraccao&)
ex1.cpp:38:13: error: ambiguous overload for ‘operator+’ in ‘4 + a’
ex1.cpp:38:13: note: candidates are:
ex1.cpp:38:13: note: operator+(int, int) <built-in>
In file included from ex1.cpp:3:0:
Fraccao.h:41:9: note: Fraccao operator+(const Fraccao&, const Fraccao&)

课程:

class Fraccao {
    int numerador;
    int denominador;

public:
    Fraccao(int num = 0, int deno = 1) : numerador(num), denominador(deno) {}

    Fraccao & operator+=(const Fraccao &fra);

    Fraccao & operator*=(const Fraccao &fra);

    operator int() const;

    const Fraccao & operator++();
    const Fraccao operator++(int);

    string getAsString() const;
};

Fraccao operator +(const Fraccao &a, const Fraccao &b);
ostream & operator<<(ostream & saida, const Fraccao & fra);

在我的主屏幕上:

void func(int n) {
    cout << n; // 
}

int main(int argc, char** argv) {
    //...
    d = a + b;
    const Fraccao h(7, 3);
    func(h);

    return 0;
}

推荐答案

您似乎没有张贴实际上导致该错误的代码.我想看起来像是

You don't seem to have posted the code that actually causes the error. I guess it looks something like

Fraccao a;
Fraccao b = a + 4;
Fraccao c = 4 + a;

问题是您的类允许与int之间的隐式转换;所以a + 4可能是

The problem is that your class allows implicit conversions both to and from int; so a + 4 could be either

int(a) + 4

a + Fraccao(4)

,没有理由选择一个.要解决歧义,您可以:

with no reason to choose one over the other. To resolve the ambiguity, you could either:

  • 如上所述,使转换明确.或
  • 声明构造函数或转换运算符(或什至都声明)explicit,以便只能隐式完成一个(或什至没有)转换.
  • make the conversion explicit, as above; or
  • declare either the constructor or the conversion operator (or even both) explicit so that only one (or even neither) conversion can be done implicitly.

这篇关于“运算符"的C ++模棱两可的重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆