是否可能重载操作符在C ++中的关联? [英] Is it possible to overload operator associativity in C++?

查看:147
本文介绍了是否可能重载操作符在C ++中的关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个有略微不对称加法的类。在投诉进来之前,它必然是不对称的。有一个转换(需要一些时间的操作),当两个对象被添加在一起时,必须发生转换,并且转换最自然地发生在正确的被加数。



<下面是一个常见的例子:

  class Foo {
char _fav;
int _prop;

public:
const char fav()const {return _fav;}
const int prop()const(return _prop;}
void changeFav //复杂的方法也改变_prop
void changeProp(int); //简单的方法
}

Foo
operator +(Foo A,Foo B){
Foo sum;
if(A.fav()!= B.fav())A.changeFav(B.fav);
sum.changeProp .prop());
return sum;
}

两个 Foo 要添加,他们需要具有相同的 _fav ,因此必须选择哪个基于 Foo 的细节,最自然的是更改左边的被加数以匹配正确的被加数。



但是,当执行时:

  Foo A,B,C; 
Foo D = A + B + C ; // D =(A + B)+ C
Foo E = A +(B + C);


b $ b

如果 A 已经具有与 C _fav c $ c>,则 D (一次更改 A)调用 changeFav 两次。 _f $ B._fav ,然后再次更改(A + B)._ fav C._fav ),一次为 E (更改 B._fav C._fav )。我喜欢后者,但希望避免强制用户使用括号进行多次添加。



有没有办法重载 operator + 的关联性以使其发生?

解决方案

从c ++标准第5节,


重载操作符第5条中指定的语法规则。


其中第5条指定运算符优先级和关联性。


I'm building a class that has a slightly asymmetric addition. Before the complaints come in, it's necessarily asymmetric. There is a conversion (operation that takes a bit of time) that has to happen when two objects are added together, and the conversion most naturally happens with respect to the right summand.

To make this concrete, here's a generic example of what's going on...

class Foo {
    char _fav;
    int _prop;

public:
    const char fav() const {return _fav;}
    const int prop() const (return _prop;}
    void changeFav(char); // complicated method that also changes _prop
    void changeProp(int); // straightforward method
}

Foo
operator + (Foo A, Foo B) {
    Foo sum;
    if (A.fav() != B.fav()) A.changeFav(B.fav);
    sum.changeProp(A.prop() + B.prop());   
    return sum;
}

In order for two Foos to be added, they need to have the same _fav, so a choice must be made as to which to convert. Based on the details of Foo, it's most natural to change the left summand to match the right summand.

However, when doing:

Foo A,B,C;
Foo D = A + B + C; // D = (A + B) + C
Foo E = A + (B + C);

if A already has the same _fav as C, then changeFav is called twice for D (once to change A._fav to B._fav and then again to change (A+B)._fav to C._fav) and once for E (to change B._fav to C._fav). I prefer the latter but want to avoid forcing the user to use parentheses for multiple additions.

Is there a way to overload the associativity of operator + to make this happen?

解决方案

From c++ standard clause 5,

Overloaded operators obey the rules for syntax specified in Clause 5.

Where clause 5 specifies operator precedence and associativity.

这篇关于是否可能重载操作符在C ++中的关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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