【问题标题】:Overload an operator twice [duplicate]两次重载运算符[重复]
【发布时间】:2014-04-24 05:57:53
【问题描述】:

在 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 +;
}

编辑:显然我不能使用返回类型作为基础重载同一个运算符两次。有什么建议吗?

【问题讨论】:

  • 不,这是不可能的。编译器不知道你想要哪个版本,它会从参数中扣除。
  • 可以重载多次,但不能通过返回类型。

标签: c++


【解决方案1】:

正如已经指出的那样,您不能仅根据返回类型来重载。所以这很好:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      来自标准文档,第 13.1.2 节,

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

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

      查看 Wiki 获取 Name Mangling 了解更多详情

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-02-25
        • 2015-06-20
        • 2011-10-27
        • 2011-11-12
        • 2012-12-22
        • 2016-09-26
        • 2018-06-01
        • 2012-04-21
        相关资源
        最近更新 更多