📄 e.htm
字号:
static const int NUM_TURNS = 5; // constant declaration int scores[NUM_TURNS]; // use of constant ...};There's a minor wrinkle, however, which is that what you see above is a declaration for NUM_TURNS, not a definition. You must still define static class members in an implementation file: const int GamePlayer::NUM_TURNS; // mandatory definition; // goes in class impl. fileThere's no need to lose sleep worrying about this detail. If you forget the definition, your linker should remind you.Older compilers may not accept this syntax, because it used to be illegal to provide an initial value for a static class member at its point of declaration. Furthermore, in-class initialization is allowed only for integral types (e.g., ints, bools, chars, etc.), and only for constants. In cases where the above syntax can't be used, you put the initial value at the point of definition: class EngineeringConstants { // this goes in the classprivate: // header file static const double FUDGE_FACTOR; ...};// this goes in the class implementation fileconst double EngineeringConstants::FUDGE_FACTOR = 1.35;This is all you need almost all the time. The only exception is when you need the value of a class constant during compilation of the class, such as in the declaration of the array GamePlayer::scores above (where compilers insist on knowing the size of the array during compilation). Then the accepted way to compensate for compilers that (incorrectly) forbid the in-class specification of initial values for integral class constants is to use what is affectionately known as "the enum hack." This technique takes advantage of the fact that the values of an enumerated type can be used where ints are expected, so GamePlayer could just as well have been defined like this: class GamePlayer {private: enum { NUM_TURNS = 5 }; // "the enum hack" makes // NUM_TURNS a symbolic name // for 5 int scores[NUM_TURNS]; // fine...};Unless you're dealing with compilers of primarily historical interest (i.e., those written before 1995), you shouldn't have to use the enum hack. Still, it's worth knowing what it looks like, because it's not uncommon to encounter it in code dating back to those early, simpler times.Getting back to the preprocessor, another common (mis)use of the #define directive is using it to implement macros that look like functions but that don't incur the overhead of a function call. The canonical example is computing the maximum of two values: #define max(a,b) ((a) > (b) ? (a) : (b))This little number has so many drawbacks, just thinking about them is painful. You're better off playing in the freeway during rush hour.Whenever you write a macro like this, you have to remember to parenthesize all the arguments when you write the macro body; otherwise you can run into trouble when somebody calls the macro with an expression. But even if you get that right, look at the weird things that can happen: int a = 5, b = 0;max(++a, b); // a is incremented twicemax(++a, b+10); // a is incremented onceHere, what happens to a inside max depends on what it is being compared with!Fortunately, you don't need to put up with this nonsense. You can get all the efficiency of a macro plus all the predictable behavior and type-safety of a regular function by using an inline function (see Item 33): inline int max(int a, int b) { return a > b ? a : b; }Now this isn't quite the same as the macro above, because this version of max can only be called with ints, but a template fixes that problem quite nicely: template<class T>inline const T& max(const T& a, const T& b){ return a > b ? a : b; }This template generates a whole family of functions, each of which takes two objects convertible to the same type and returns a reference to (a constant version of) the greater of the two objects. Because you don't know what the type T will be, you pass and return by reference for efficiency (see Item 22).By the way, before you consider writing templates for commonly useful functions like max, check the standard library (see Item 49) to see if they already exist. In the case of max, you'll be pleasantly surprised to find that you can rest on others' laurels: max is part of the standard C++ library.Given the availability of consts and inlines, your need for the preprocessor is reduced, but it's not completely eliminated. The day is far from near when you can abandon #include, and #ifdef/#ifndef continue to play important roles in controlling compilation. It's not yet time to retire the preprocessor, but you should definitely plan to start giving it longer and more frequent vacations. Back to Item 1: Prefer const and inline to #define.Continue to Item 3: Prefer new and delete to malloc and free.Item 2: Prefer <iostream> to <stdio.h>.Yes, they're portable. Yes, they're efficient. Yes, you already know how to use them. Yes, yes, yes. But venerated though they are, the fact of the matter is that scanf and printf and all their ilk could use some improvement. In particular, they're not type-safe and they're not extensible. Because type safety and extensibility are cornerstones of the C++ way of life, you might just as well resign yourself to them right now. Besides, the printf/scanf family of functions separate the variables to be read or written from the formatting information that controls the reads and writes, just like FORTRAN does. It's time to bid the 1950s a fond farewell.Not surprisingly, these weaknesses of printf/scanf are the strengths of operator>> and operator<<. int i;Rational r; // r is a rational number...cin >> i >> r;cout << i << r;If this code is to compile, there must be functions operator>> and operator<< that can work with an object of type Rational (possibly via implicit type conversion see Item M5). If these functions are missing, it's an error. (The versions for ints are standard.) Furthermore, compilers take care of figuring out which versions of the operators to call for different variables, so you needn't worry about specifying that the first object to be read or written is an int and the second is a Rational.In addition, objects to be read are passed using the same syntactic form as are those to be written, so you don't have to remember silly rules like you do for scanf, where if you don't already have a pointer, you have to be sure to take an address, but if you've already got a pointer, you have to be sure not to take an address. Let C++ compilers take care of those details. They have nothing better to do, and you do have better things to do. Finally, note that built-in types like int are read and written in the same manner as user-defined types like Rational. Try that using scanf and printf!Here's how you might write an output routine for a class representing rational numbers: class Rational {public: Rational(int numerator = 0, int denominator = 1); ...private: int n, d; // numerator and denominatorfriend ostream& operator<<(ostream& s, const Rational& r);};ostream& operator<<(ostream& s, const Rational& r){ s << r.n << '/' << r.d; return s;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -