Effective C ++ ## 02 Terms: try to const, enum, inline replace #define ##

Theme  C ++

This clause can also be changed to "may be replaced with a compiler preprocessor," because #define there are a lot of problems and inconveniences.

#define ASPEC 1.6454

When you use this constant but get a compiler error message may be confusing, because the error message mentioned 1.6454 but does not mention the name itself, especially the amount and others or defined in another header file more trouble.

But instead  const double ASPEC = 1.6454 this situation would not arise.

When const, the pointer should be noted that when combined with the relative position of the '*' and the const;

Another issue to note is that if you want to set up in class in such a scope for variables of this class, then let it be a static member:

class G
{

static const int num = 5;
On int [whether];

};

However, num is a constant rather than a declarative definition of style, usually C ++ requires you to provide a definition of style to anything you use.

But if it is a class-specific constant is static, and is an integer type (integral type, such as int, char, bool), need special treatment.

I do not take their address, you can declare and use them without having to provide a definition of style.

But if you take the address of a class-specific constants, or even if you do not take its address, but the compiler was (incorrectly) insisted on seeing a defined style,

You must also provide a definition formula is as follows:

G :: const int num;

· # Define is not to provide any package, that is not something private #define like, but const can.

Another useful things like enum hack is added the following code in the class:

enum {Now} = 5;

As a generation 5, said with a Nun, and avoid using your hands to get the address of integer constants, enum can complete this constraint. And it was practical, often used.

If you have wanted to learn c ++ programmers, you can come to our C / C ++ learning buckle qun: 589348389,
free delivery C ++ Video Tutorial Oh!
Each 20:00 I will live in the group to explain the C / C ++ knowledge, welcome everyone to learn Oh.

Guess you like

Origin blog.csdn.net/XZQ121963/article/details/90742411