我正在阅读有效的 C++。他们举了一个例子如下:
class Rational{
public : Rational (int num=0, int deno=1);
private : int n,d;
friend Rational operator*(const Rational &lhs, const Rational &rhs);
}
Rational& operator*(const Rational& lhs, const Rational& rhs)
{
static Rational result;
result = f(lhs.n*rhs.n, lhs.d*rhs.d) //some function f which multiply num
//and denom which returns Rational type
return result;
}
bool operator==(const Rational& lhs, const Rational& rhs);
int main()
{
Rational a,b,c,d;
.....
if((a*b)==(c*d)){
....
}
else {
.....
}
}
为什么比较 (a*b)==(c*d) 总是评估为真?
== 运算符将被评估为 if(operator==(operator*(a,b),operator*(c,d))) Effective C++ 说 - 运算符 == 将被要求比较静态 Rational 对象的值内部运算符 * 与 * 运算符内部的静态 Rational 对象的值。为什么这些静态值总是相等的?