C++ 函数
内联函数的定义及使用
#include <iostream>
using namespace std;
// 内联函数
// 内联函数声明前加上关键字inline
// 内联函数占用内存大,但运行速度快
inline double square(double x){
return x * x;
}
int main() {
double a = square(5.0);
cout << "a : " << a << endl;
return 0;
}
引用变量的定义,共享变量
#include <iostream>
using namespace std;
// 引用变量
// 使用类型标识符,int &指向int的引用,rodents和rats指向相同的值和内存单元
void referenceVariable(){
int rats;
//int *rodents = &rats;
int & rodents = rats;
rats = 10;
cout << "rats Value is : " << rats << endl;
cout << "rats Address is : " << &rats << endl;
cout << "rats Value is : " << rodents << endl;
cout << "rats Address is : " << &rodents << endl;
// rats Value is : 10
// rats Address is : 0xffffcbc4
// rats Value is : 10
// rats Address is : 0xffffcbc4
}
int main() {
referenceVariable();
return 0;
}
定义和使用函数模板
#include <iostream>
using namespace std;
// 函数模板的定义
//template <class Any>
template <typename Any>
void Swap(Any &a, Any &b){
Any temp;
temp = a;
a= b;
b = temp;
}
void useTemSwap(){
int i = 10;
int j = 20;
cout << "i, j =" << i << "," << j << endl;
Swap(i, j);
cout << "i, j =" << i << "," << j << endl;
double n = 5.0;
double m = 10.0;
cout << "n, m =" << n << "," << m << endl;
Swap(n, m);
cout << "n, m =" << n << "," << m << endl;
}
int main() {
useTemSwap();
return 0;
}
模板函数的实例化和具体化:隐式实例化、显示实例化
// 模板实例化
// 隐式实例化
template void Swap<int> (int &, int &);
// 显示实例化
template <> void Swap<int>(int &, int &);
template <> void Swap(int &, int &);