重载操作员两次 [英] Overload an operator twice

查看:162
本文介绍了重载操作员两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有可能在C ++上重载相同的操作符两次?

It's possible to overload the same operator twice on C++?

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

When I try to overload the + operator using the return type as a base, the compiler show me an error.

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


b $ b

这是我的代码:

This is my code:

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



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

Apparently I cannot overload the same operator twice using the return type as a base. Suggestions?

推荐答案

正如已经指出的,你不能只对返回类型重载。所以这很好:

As has been pointed out, you cannot overload beased on return type alone. So this is fine:

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

但不是:

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

但大多数时候,对于给定的问题有有效和简单的解决方案。例如,在像您的情况下,您希望以下工作:

But most of the time there are valid and simple solutions to a given problem. For instance, in a situation like yours, where you want the following to work:

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

那么一个常见的策略是给予 Bar 一个隐式转换构造函数:

then a common strategy is to either give Bar an implicit converting constructor:

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

或给予 Foo / p>

or give Foo a conversion operator:

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

请注意,您不能标记运算符 explicit 如果没有C ++ 11编译器。

Note you can't mark the operator explicit if you don't have a C++11 compiler.

这篇关于重载操作员两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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