【发布时间】:2012-11-04 09:17:16
【问题描述】:
在 c++ 中,我实现了一个 integer 类,并重载了 operator ^ 以作为幂函数。
integer integer::operator^ (const integer& rhs){
return integer(pow(this->.i, rhs.i));
}
这适用于两个操作数。
integer i1, i2, i3 ;
i4 = i1 ^ i2 ^ i3;
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!
【问题讨论】:
-
-1:向我们展示一些真正有价值的代码。我不是通灵者(没有人是),所以我看不出你对
operator^的定义是什么。 -
即使您可以更改关联性(您不能),优先级也会令人困惑;
a * b^c将被解析为(a*b)^c。通常最好不要重载运算符来执行与内置版本在概念上不同的操作。 -
@user1705796 是的,你真的不想那样做。拥有 '^' 作为权力会让任何习惯使用 '^' 表示 XOR(即,每个 C++ 开发人员)的人感到困惑。此外,“数学上”并没有错。左/右关联性不是数学属性(尽管关联性是 - ^ 顺便说一下不是关联性的,(a^b)^c != a^(b^c)),它只是一个约定。
-
@user1705796:认真的吗?你认为“but Y -ve”是你可以在公共场合输入并期望人们容忍你的东西吗?如果你不能抽出五秒钟来打出一个英文句子,我们为什么要花五分钟来思考你的问题?
标签: c++ operators operator-overloading xor