关联性顺序相反的C ++重载运算符 [英] C++ overloaded operator with reverse order of associativity

查看:99
本文介绍了关联性顺序相反的C ++重载运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很难找到一个标题...(我不是英语为母语的人.)

It was very hard to come up with a title... (I'm not a native English speaker.)

struct A
{
    int value;
    A operator+(int i) const
    {
        A a;
        a.value=value+i;
        return a;
    };
};
int main(){
    A a;
    a.value=2;
    a=a+2;
    return 0;
}

此代码可以按预期方式编译/运行,但是当我将a = a + 2更改为a = 2 + a时,它将不再编译. GCC给我这个错误:

This code compiles/works as expected, but when I change a=a+2 to a=2+a, it won't compile anymore. GCC gives me this error:

no match for "operator+" in "2 + a"

有什么办法可以使2 + a像a + 2一样工作吗?

Is there any way to somehow make 2+a work just like a+2?

推荐答案

您需要一个免费的函数,该函数在 类之后定义

You need a free function, defined after the class

struct A
{
   // ...
};

A operator+(int i, const A& a)
{
  return a+i; // assuming commutativity
};

另外,您还可以考虑在A中将A& operator+=(int i);定义为将operator+的两个版本都实现为自由函数.您可能还对Boost.Operators或其他帮助程序简化A感兴趣,请参阅我的个人资料中的两个选项.

also, you might consider defining A& operator+=(int i); in A an implement both versions of operator+ as free functions. You might also be interested in Boost.Operators or other helpers to simplify A, see my profile for two options.

这篇关于关联性顺序相反的C ++重载运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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