## CSDN博客

### Effective C++ 2e Item23

class Rational {
public:
Rational(int numerator = 0, int denominator = 1);

...

private:
int n, d;              // 分子和分母

friend
const Rational                      // 参见条款21：为什么
operator*(const Rational& lhs,    // 返回值是const
const Rational& rhs)
};

inline const Rational operator*(const Rational& lhs,
const Rational& rhs)
{
return Rational(lhs.n * rhs.n, lhs.d * rhs.d);
}

Rational a(1, 2);                // a = 1/2
Rational b(3, 5);                // b = 3/5
Rational c = a * b;              // c 为 3/10

// 写此函数的第一个错误方法
inline const Rational& operator*(const Rational& lhs,
const Rational& rhs)
{
Rational result(lhs.n * rhs.n, lhs.d * rhs.d);
return result;
}

// 写此函数的第二个错误方法
inline const Rational& operator*(const Rational& lhs,
const Rational& rhs)
{
Rational *result =
new Rational(lhs.n * rhs.n, lhs.d * rhs.d);
return *result;
}

Rational w, x, y, z;

w = x * y * z;

// 写此函数的第三个错误方法
inline const Rational& operator*(const Rational& lhs,
const Rational& rhs)
{
static Rational result;      // 将要作为引用返回的
// 静态对象

lhs和rhs 相乘，结果放进result；

return result;
}

bool operator==(const Rational& lhs,      // Rationals的operator==
const Rational& rhs);     //

Rational a, b, c, d;

...

if ((a * b) == (c * d)) {

处理相等的情况;

} else {

处理不相等的情况;

}

if (operator==(operator*(a, b), operator*(c, d)))

inline const Rational operator*(const Rational& lhs,
const Rational& rhs)
{
return Rational(lhs.n * rhs.n, lhs.d * rhs.d);
}

0 0