Excerpt from the Houtie version of effective C + + (third edition)
Clause I
C + + as a multi-paradigm fusion language, can be seen as a language of the Commonwealth, it contains the four major sub-languages:
- C. C + + is based on, many times C + + for the problem of the solution is actually higher-level C solution, but the C language limitations: No template, no exception handling, no overloading.
- OO C + +. Includes classes, encapsulation, inheritance, polymorphism, dynamic binding.
- Template C + +. This is part of the C + + paradigm.
- Stl. Consists of three main parts. Container (containers), iterator (iterator), Algorithm (algorithm).
The code of effective programming varies depending on what part of C + + you use.
Clause II Replace # define with const, enum, inline as possible
The reason is that, #define RATIO 1.6, the replaced token name RATIO may never appear in the symbol table, which poses many difficulties for debug.
When you use const instead of # define as a constant, you need to be aware of the use of strings, which is "right-to-left read rules":
Const Char Const " Meyers "
A constant pointer variable authorname a char (s) that points to a constant.
In addition, #define不具备封装性, such as the exclusive constant as class:
class gameplayer{private: staticconstint5; int Scores[numturns]; ...};
However, the above statement does not pass through some compilers, so a definition is required:
class gameplayer{private: staticconstint numturns; int Scores[numturns]; ...}; Const int 5;
There is also a compensation practice using the "enum hack", which takes advantage of the characteristics of the emun instead of constants to limit the constant member variables of an undesirable address:
class gameplayer{private: enum5}; int Scores[numturns]; ...};
There are too many drawbacks to defining a function using # define, for example:
#define Call_with_max (A, B) f ((a) > (b)? (a): (b) int a = 5 , B = 0 ; Call_with_max ( ++a,b); // A is incremented two times Call_with_max (++a,b + 10 ); // A is incremented once <typename t>inline void Callwithmax (const T & A, const t& b) {f (a > b? A:B);}
- For simple constants It is best to replace # define with a const object or enum
- For macro functions, it is best to replace the # define function with the inline function
Effective C + + (third edition) Notes----The first part to get used to C + +