千里之行,始于足下

2007年12月10日 #

《effective c++ II》学习笔记 Item 2 Prefer iostream to stdio.h

关键词:safety, extensibility

int i;
Rational r;                           
// r is a rational number

cin 
>> i >> r;
cout 
<< i << r;


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

绕开scanf(),printf()恼人的格式要求。使用便捷,安全的<<,>>操作符。

最后,
#include<iostream.h>是全局意义上的库函数声明,容易冲突。
#include<iostream>是STL的写法,要名字空间std::声明。


posted @ 2007-12-10 16:12 rednight 阅读(218) | 评论 (0)编辑 收藏

《effective c++ II》学习笔记 Item1 Prefer const and inline to #define

宏定义
#define ASPECT_RATIO 1.653

主要是宏在预编译的时候被移除,不加入编译器编译,不利于错误的检测,给调试维护带来一定困难。
因而用
const double ASPECT_RATIO = 1.653;

代替。
存在2个小问题需要注意:
1)    指针常量问题
const char * const authorName = "Scott Meyers";

需要2次使用”const”
2)    在类的定义中
class GamePlayer {
private:
  
static const int NUM_TURNS = 5;    // constant declaration
  int scores[NUM_TURNS];             // use of constant
  
};

此外,还必须在.cpp文件中予以定义:
const int GamePlayer::NUM_TURNS;      // mandatory definition;
                                      
// goes in class impl. file


值得注意的是老的编译器不支持这种表达方式,因此要采用如下的方式:
 
class EngineeringConstants {      // this goes in the class
private:                          // header file
  static const double FUDGE_FACTOR;
  
};

// this goes in the class implementation file
const double EngineeringConstants::FUDGE_FACTOR = 1.35;


这种情形下如果要在类中定义常量数组,需要采用枚举类型做一折中处理:
class GamePlayer {
private:
  
enum { NUM_TURNS = 5 };    // "the enum hack" — makes
                             
// NUM_TURNS a symbolic name
                             
// for 5
  int scores[NUM_TURNS];     // fine

};


避免
#define max(a,b) ((a) > (b) ? (a) : (b))

这种写法。
采用内连函数:
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)
return a > b ? a : b; }

总结:并不是说不使用宏,要明确地知道使用宏后可能会引起的后果,减少有歧义的情况发生。
 

posted @ 2007-12-10 14:36 rednight 阅读(197) | 评论 (0)编辑 收藏

2007年12月6日 #

《effective c++ II》Introduction

内容见http://www.cppblog.com/rednight/articles/37913.html
为啥只有随笔能显示在主页面上呢?

posted @ 2007-12-06 17:08 rednight 阅读(248) | 评论 (0)编辑 收藏

仅列出标题