C++ effective reading notes

1: Try to use the compiler without preprocessing (try to use const and inline instead of #define)

instance1:

#define DRV_L3_U32BIT_OFFSET (5)

Can be replaced with const uchar DRV_L3_U32BIT_OFFSET = 5. #define does not exist in the symbol table.

#define DRV_DEVM_L2MC_NAME   “L2MC” 

Can be replaced with const char * const DRV_DEVM_L2MC_NAME = "L2MC"

It is also very convenient to define a constant of a certain class. To limit the constant to the class, first make it a member of the class; in order to ensure that there is only one copy of the constant at most, define it as a static member.

class GamePlayer

{

private:

  static const int NUM_TRUNS = 5;           //constant eclaration

  int scores[NUM_TRUNS];

  ...

};

The above statement is a declaration of NUM_TRUNS, not a definition, and the static member variables of the class need to be defined in the implementation code of the class.

const int  GamePlayer::NUM_TRUNS;     //  mandatory definition(强制)  //goes in class impl.file

Older compilers will not accept this syntax, thinking that it is illegal to define initial values ​​for static members of a class when they are declared; and only initialization integers are allowed in a class, and only constants.

Solution:

class EngineeringConstants       //goes in the class header file

{

private:

  static const double FUDGE_FACTOR;

  ...

};

 

//goes in the class implements file

const double EngineeringConstants ::  FUDGE_FACTOR = 1.35;

When a class needs to use the constants of this class during compilation, such as the declaration of the GamePlayer::scores array, the compiler must know the size of the array during compilation.

Solution: Borrow the enum method to solve. The principle of enumeration can be used if the int type is required.

class GamePlayer

{

private:

  enum {NUM_TRUNS = 5} //constant eclaration

  int scores[NUM_TRUNS];

  ...

};

instance2:

#define  Max(a ,b) ((a) > (b) ? (a):(b))

Auto increment/decrement operation exception

inline int max(int a,int b)

{

  return a > b ? a :b;

}

 

template<class T>

inline const T& Max(const T& a,const T& b) //Because you don't know the type of T, passing a reference when returning can improve efficiency

{

  return a > b ? a :b;

}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324484565&siteId=291194637