When replacing #defines with constants, two special cases are worth mentioning. The first is defining constant pointers. Because constant definitions are typically put in header files (where many different source files will include them), it’s important that the pointer be declared const, usually in addition to what the pointer points to. To define a constant char*-based string in a header file, for example, you have to write const twice:
- const char * const authorName = "Scott Meyers";
For a complete discussion of the meanings and uses of const, especially in conjunction with pointers, see Item 3. However, it’s worth reminding you here that string objects are generally preferable to their char*-based progenitors, so authorName is often better defined this way:
- const std::string authorName("Scott Meyers");
这里可见 build-in类型在C++(www.cppentry.com)中不受欢迎。如果你不打算使用C风格的C++(www.cppentry.com)。使用 std::string总是比const char *要好一些。
C接口中常见的void **类型,在C++(www.cppentry.com)风格的程序中也不多见。
The second special case concerns class-specific constants. To limit the scope of a constant to a class, you must make it a member, and to ensure there’s at most one copy of the constant, you must make it a static member:
- class GamePlayer {
- private:
What you see above is a declaration for NumTurns, not a definition. Usually, C++(www.cppentry.com) requires that you provide a definition for anything you use, but class-specific constants that are static and of integral type (e.g., integers, chars, bools) are an exception. As long as you don’t take their address, you can declare them and use them without providing a definition. If you do take the address of a class constant, or if your compiler incorrectly insists on a definition even if you don’t take the address, you provide a separate definition like this:
You put this in an implementation file, not a header file. Because the initial value of class constants is provided where the constant is declared (e.g., NumTurns is initialized to 5 when it is declared), no initial value is permitted at the point of definition.