Item 24: Declare non-member functions when type...

  1. 1. Part 4: Designs and Declarations
  2. 2. Things To Remember
  3. 3. Key Points
  4. 4. Code

This article is one of <Effective C++> reading notes.

Part 4: Designs and Declarations

Item 24: Declare non-member function when type conversions should apply to all parameters.


Things To Remember

  • If you need type conversions on all parameters to a function (include the one pointed to by this pointer), the function must be a non-member.

Key Points

  • The opposite of a member function is a non-member function, not a friend function.
  • Wherever you can avoid friend functions, you should, because, much as in real life, friends are often more trouble than they’re worth.
  • 在设计 C++ 程序时,第一考虑的应该是怎样用最少的 C++ 知识来达成目地。重载操作法,对于不使用 template 的场合,多半不是必要的。所以,更偏向于先实现一个 const Rational MulRational(const Rational& lhs, const Rational& rhs) 的函数,再根据需要实现 operator* 调用它。

Code

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
#include "stdafx.h"
class Rational {
public:
true// ctor is deliberately not explicit;
true// allows implicit int-to-Rational conversions
trueRational(int numerator = 0, int denominator = 1);
true// accessors for numerator and denominator - see Item 22
trueint numerator() const;
trueint denominator() const;
true// for why this function declared the way it is,
true// think of this: if (a * b = c) [Item 3]
true/* const Rational operator*(const Rational& rhs) const; */
private:
true// ...
};
const Rational operator*(const Rational& lhs, const Rational& rhs)
{
truereturn Rational(lhs.numerator() * rhs.numerator(),
truetruetruetruetruelhs.denominator() * rhs.denominator());
}
int main()
{
trueRational oneEight(1, 8);
trueRational oneHarf(1, 2);
trueRational result;
trueresult = oneHarf * 2; // fine
true/* result = 2 * oneHarf; // with member operator*, error! */
trueresult = 2 * oneHarf;
truereturn 0;
}