1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
class Rational {
public:
Rational(int numerator = 0, int denominator = 1);
private:
int n, d;
friend const Rational operator*(const Rational& lhs, const Rational& rhs);
};
// 函数返回一个reference指向result,
// 但result是local对象,在函数退出前就被销毁了。
const Rational& operator*(const Rational& lhs, const Rational& rhs) {
Rational result(lhs.n*rhs.n, lhs.d*rhs.d); // bad code
return result;
}
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;
// 同一个语句内调用了两次operator*,却没有合理的办法调用delete
w = x * y * z; // operator*(operator*(x,y), z)
// use static
const Rational& operator*(const Rational& lhs, const Rational& rhs) {
static Rational result;
result = Rational(lhs.n*rhs.n, lhs.d*rhs.d);
return result;
}
bool operator==(const Rational& lhs, const Rational& rhs);
Rational a, b, c, d;
if ((a*b) == (c*d)) {
// always return true
}
if (operator==(operator*(a,b), operator*(c,d))) {
// 中间返回相同的result对象,所以始终返回true
}
|