1, inline 函数避免函数调用的开销,将函数指定为 inline 函数,(通常)就是将它在程序中每个调用点上“内联地”展开。
// inline version: find longer of two strings
inline const string &
shorterString(const string &s1, const string &s2)
{
return s1.size() < s2.size() ? s1 : s2;
}
2,把 inline 函数的定义放在头文件中 ,可以确保在调用函数时所使用的定义是相同的,并且保证在调用点该函数的定义对编译器可见。
3,每个成员函数都有一个额外的、隐含的形参 this。在调用成员函数时,形参 this 初始化为调用函数的对象的地址。为了理解成员函数的调用,可考虑下面的语句:
bool same_isbn(const Sales_item &rhs) const
{ return isbn == rhs.isbn; }
// pseudo-code illustration of how a call to a member function is translated
Sales_item::same_isbn(&total, trans);
可以理解跟在 Sales_item 成员函数声明的形参表后面的 const 所起的作用了:const 改变了隐含的 this 形参的类型。在调用 total.same_isbn(trans) 时,隐含的 this 形参将是一个指向 total 对象的 const Sales_Item* 类型的指针。
4, 函数指针是指指向函数而非指向对象的指针。像其他指针一样,函数指针也指向某个特定的类型。函数类型由其返回类型以及形参表确定,而与函数名无关:
bool (*pf)(const string &, const string &);
函数指针类型相当地冗长。使用 typedef 为指针类型定义同义词,可将函数指针的使用大大简化:
typedef bool (*cmpFcn)(const string &, const string &);
// compares lengths of two strings
bool lengthCompare(const string &, const string &);
cmpFcn pf1 = 0; // ok: unbound pointer to function
cmpFcn pf2 = lengthCompare; // ok: pointer type matches function's type
pf1 = lengthCompare; // ok: pointer type matches function's type
pf2 = pf1; // ok: pointer types match