Gri*_*han 3 c++ operator-overloading operators xor
在c ++中,我实现了一个integer类,我重载operator ^为power函数.
integer integer::operator^ (const integer& rhs){
return integer(pow(this->.i, rhs.i));
}
Run Code Online (Sandbox Code Playgroud)
这适用于两个操作数.
integer i1, i2, i3 ;
i4 = i1 ^ i2 ^ i3;
Run Code Online (Sandbox Code Playgroud)
i4数学上的值是错误的,因为关联性需要从右到左.我怎么解决这个问题?如何更改关联性?
我得到了合理的答案,我学到了:
-We can't change associativity or priority of an operator.
-Good is Not to overload operators to do something conceptually different to
the built-in versions
-Even compiler can't support; it hard to implement!
Run Code Online (Sandbox Code Playgroud)
zne*_*eak 10
您不能通过重载来更改C++中运算符的关联性或优先级.这些规则硬连线到语言语法中.
C++标准说(§13.5.6,强调我的):
运算符函数应该是非静态成员函数或者是非成员函数,并且至少有一个参数,其类型是类,对类的引用,枚举或对枚举的引用.无法更改运算符的优先级,分组或操作数. 每种类型预定义的operator =,(一元)&,和(逗号)的含义可以改变[...]
^运算符不仅是左关联的,而且它的优先级也非常低.幂运算符的正确优先级应高于乘法(因此该表的优先级为4或更高),但它具有优先级10 - 这意味着在它之前评估偶数加法和减法.1 + 2 ^ 3 * 4将被解析为(1 + 2) ^ (3 * 4),而数学上正确的幂运算符应解析为1 + (2 ^ 3) * 4.
如果可以修改运算符的关联性或优先级,则会产生巨大的,巨大的语法混乱.我的拙见是,你不应该试图让^运营商超负荷将其用作电力运营商.我宁愿power在课堂上制作一个方法.
| 归档时间: |
|
| 查看次数: |
1334 次 |
| 最近记录: |