内联函数:
常规函数和内联函数之间的主要区别不在于编写方式,而在于C++编译器如何将它们组合到程序中。
对于内联代码,程序无需跳到另一个位置处执行代码,然后再跳回来。因此,内联函数的运行速度比常规函数稍快,但代价是需要占用更多的内存。
创建引用变量:
引用更接近const 指针,必须在创建时进行初始化,一旦与某个变量关联起来,就将一直效忠于它,也就是说:
int & rodents = rats;
实际上是下述代码的伪装表示:
int * const pr = &rats;
其中,引用rodents扮演的角色与表达式*pr相同。
函数重载:
术语多态(polymorphism)指的是有多种形式,因此函数多态允许函数可以有多种形式。类似地,术语函数重载(function overloading)指的是可以有多个同名的函数,因此对名称进行了重载。
函数模板:
第一行指出,要建立一个模板,并将类型命名为Any。关键字template和class是必须的,除非可以使用关键字typename 代替class。另外,必须使用尖括号。例子,如:twoswap.cpp
#include <iostream>
template <class Any>
void Swap (Any &a,Any &b);
struct job
{
char name[40];
double salary;
int floor;
};
//explicit specialization
template <> void Swap <job> (job &j1, job &j2);
void Show (job &j);
int main()
{
using namespace std;
cout.precision (2);
cout.setf(ios::fixed, ios::floatfield);
int i = 10,j = 20;
cout <<"i,j = "<< i << ","<< j << ".\n";
cout<<"Useing compiler-generated int swapper: \n";
Swap(i,j); //generates void Swap(int &,int &)
cout << "Now i,j = "<< i << ","<< j << ". \n";
job sue = {"Susan Yaffee",73000.60,7};
job sidney = {"Sidney Taffee", 78060.72,9};
cout << "Before job swapping: \n";
Show(sue);
Show (sidney);
Swap(sue,sidney); //uses void Swap(job &,job &)
cout << "After job swapping: \n";
Show(sue);
Show(sidney);
getchar();
return 0;
}
template <class Any>
void Swap(Any &a,Any &b) //general version
{
Any temp;
temp = a;
a = b;
b = temp;
}