重载操作员两次

时间:2014-04-24 05:57:53

标签: c++

可以在C ++上重载相同的运算符两次吗?

当我尝试使用返回类型作为基础重载+运算符时,编译器会显示错误。

bigint.h:41:9: error: ‘std::string BigInt::operator+(BigInt)’ cannot be overloaded
bigint.h:40:9: error: with ‘BigInt BigInt::operator+(BigInt)’

这是我的代码:

·H:

BigInt operator + (BigInt);
string operator + (BigInt);

.CC:

BigInt BigInt::operator + (BigInt M){

    if (this->number.size() != M.number.size())
        fixLength (this->number, M.number);

    // Call Sum;
    this->number = Sum (this->number, M.number);

    return (*this);
}

string BigInt::operator + (Bigint M){

    // Call BigInt overload +;
}

编辑:显然我不能使用返回类型作为基础重载相同的运算符两次。建议?

3 个答案:

答案 0 :(得分:4)

正如已经指出的那样,单独返回类型不能超载。所以这很好:

Foo operator+(const Foo&, const Foo&);
Foo operator+(const char*, double);

但这不是:

Foo operator+(const Foo&, const Foo&);
Bar operator+(const Foo&, const Foo&);

但大部分时间都存在针对特定问题的有效且简单的解决方案。例如,在像您这样的情况下,您需要以下工作:

Foo a, b;
Foo c = a + b;
Bar bar = a + b;

然后一个常见的策略是给Bar隐式转换构造函数:

struct Bar
{
  Bar(const Foo& foo) { .... }
};

或给Foo转化运营商:

struct Foo
{
  explicit operator Bar() { .... }
  ....
};

请注意,如果您没有C ++ 11编译器,则无法标记运算符explicit

答案 1 :(得分:3)

C ++中的方法重载是通过参数列表,而不是返回值..所以在你的情况下,这两个方法是不明确的,编译器无法分辨使用哪一个(它们具有相同的参数列表)

答案 2 :(得分:0)

不,您不能根据返回类型重载。

来自标准文档,第13.1.2节,

Function declarations that differ only in the return type cannot be overloaded.

这意味着方法只有在参数不同时才会重载。与C ++一样,方法的返回类型不被视为方法签名的一部分。

检查Wiki Name Mangling以获取更多详细信息