Effective C++メモ(1)CからC++へ

7946 ワード


条項1:define(前処理)ではなくconstとinline(コンパイラ)をできるだけ使用する
理由:
1.#define(   )                  ,    ,                   ,    const 
     
2. #define                       : 
     
#define max(a,b) ((a) > (b) ? (a) : (b)))
  
    
            : 
     

int a = 5, b = 0;
max(++a, b);//aの値は2回増加した
max(++a, b+10);//aの値は1回しか増加していません
max                  !               : 
     

template
inline const T& max(const T& a, const T& b)
{ return a > b ? a : b; }

  
    

 

 
     
1constconstconst(eg: const char * const authorName = "Scott Meyers";); 
     
2、                      ,           。 
     

  
    

 


  
    

 

  2:   “iostream”   “stdio.h
  
    
 
     
a.scanf/printf           ,       ;     Cint,float,char,doubleiostream  >> << 
     

class Rational {
public:
    Rational(int numerator = 0, int denominator = 1);
    ...
private:
    int n, d;//ぶんし
    friend ostream& operator<<(ostream& s, const Rational& );
};
 
ostream& operator<<(ostream& s, const Rational& r)
{
    s<< r.n << '/' << r.d;
    return s;
}

  
    

 

 
     
1"friend ostream& operator<<(ostream& s, const Rational& );"    operator<<operator<<   Rationalconst
2
、 ,iostream C stream

  
    

 


  
    

 

  3new delete   malloc free
  
    
 
     
malloc  free(    )            ,   malloc         ,                ,           ,                    ,       , new delete 
     

  
    

 

 
     
new/delete malloc/free   ,               ,               malloc  new 
     

  
    

 


  
    

 

  4C++     
   /**/ 
     

if ( a > b ) {
   /*  int temp = a; /* swap a and b */
        a = b;
        b = temp;
    */
}
        // 
     

if ( a > b ) {
   /*  int temp = a; //swap a and b
        a = b;
        b = temp;
    */
}
  
    

 
注意:
古いc専用のプリプロセッサはc++スタイルの注釈を処理することを知らないので、以下のような場合、予想通りにはいかない.
#define light_speedp 3e8   //m/sec (in a vacuum)