C++ 函数

内联函数的定义及使用

  1. #include <iostream>
  2. using namespace std;
  3. // 内联函数
  4. // 内联函数声明前加上关键字inline
  5. // 内联函数占用内存大,但运行速度快
  6. inline double square(double x){
  7. return x * x;
  8. }
  9. int main() {
  10. double a = square(5.0);
  11. cout << "a : " << a << endl;
  12. return 0;
  13. }

引用变量的定义,共享变量

  1. #include <iostream>
  2. using namespace std;
  3. // 引用变量
  4. // 使用类型标识符,int &指向int的引用,rodents和rats指向相同的值和内存单元
  5. void referenceVariable(){
  6. int rats;
  7. //int *rodents = &rats;
  8. int & rodents = rats;
  9. rats = 10;
  10. cout << "rats Value is : " << rats << endl;
  11. cout << "rats Address is : " << &rats << endl;
  12. cout << "rats Value is : " << rodents << endl;
  13. cout << "rats Address is : " << &rodents << endl;
  14. // rats Value is : 10
  15. // rats Address is : 0xffffcbc4
  16. // rats Value is : 10
  17. // rats Address is : 0xffffcbc4
  18. }
  19. int main() {
  20. referenceVariable();
  21. return 0;
  22. }

定义和使用函数模板

  1. #include <iostream>
  2. using namespace std;
  3. // 函数模板的定义
  4. //template <class Any>
  5. template <typename Any>
  6. void Swap(Any &a, Any &b){
  7. Any temp;
  8. temp = a;
  9. a= b;
  10. b = temp;
  11. }
  12. void useTemSwap(){
  13. int i = 10;
  14. int j = 20;
  15. cout << "i, j =" << i << "," << j << endl;
  16. Swap(i, j);
  17. cout << "i, j =" << i << "," << j << endl;
  18. double n = 5.0;
  19. double m = 10.0;
  20. cout << "n, m =" << n << "," << m << endl;
  21. Swap(n, m);
  22. cout << "n, m =" << n << "," << m << endl;
  23. }
  24. int main() {
  25. useTemSwap();
  26. return 0;
  27. }

模板函数的实例化和具体化:隐式实例化、显示实例化

  1. // 模板实例化
  2. // 隐式实例化
  3. template void Swap<int> (int &, int &);
  4. // 显示实例化
  5. template <> void Swap<int>(int &, int &);
  6. template <> void Swap(int &, int &);