注:学习侯捷老师翻译的Effective C++
T2:
e.g:
// 将a和b中的较大值,传入f
#define CALL_WITH_MAX(a, b) f((a) > (b) ? (a) : (b))
以上写法,对于如下使用方式会存在问题:
int a = 3, b = 0;
CALL_WITH_MAX(++a, b); // a被加了两次
CALL_WITH_MAX(++a, b+10); // a被加了一次
可以用template inline函数来代替#define:
template <typename T>
inline void call_with_max(const T& a, const T& b) {
f(a > b ? a : b);
}
记住:
对于形似函数的宏定义,可以考虑用 内联函数代替
T3
const迭代器 const_iterator
std::vector<int>::const_iterator itt
const std::vector<int>::iterator Citor
const用途:
const operator* (const T& lhs, const T& rhs); // 避免了(a * b) = c的费解
const T& operator[] (std::size_t pos) const;
T& operator[] (std::size_t pos);
const成员函数不可以更改对象内任何non-static成员变量