C++知识总结--重载与模板

it2025-12-31  13

1. 默认参数要为某个参数设置默认值,则必须为它右边所有参数提供默认值

int harpo(int n, int m = 0, int j = 5) /* VALID */ int chico(int n, int m = 6, int j) /* INVALID */ int groucho(int k = 0, int m = 2, int n = 3) /* VALID */

 

2. 函数重载函数的参数列表,也称为函数的特征标。是特征标,而不是函数返回类型使得可以对函数进行重载。p.s. 编译器在检查函数特征标时,把类型引用和类型本身视作同一个特征标。仅当函数基本上执行相同的任务,但使用不同形式的数据时,才应采用函数重载。

 

3. 函数模板:

template <class Any> /* 也可以写成 template <typename Any> */ void Swap(Any &a, Any &b) { Any temp; temp = a; a = b; b = temp; }

 

程序示例:

#include <iostream>template <typename Any> void Swap(Any &a, Any &b); /* 声明 */ int main() { using namespace std; int i = 10; int j = 20; Swap(i, j); cout<<"After swap, i = "<<i<<", j = "<<j<<endl; return 0; } template <typename Any> void Swap(Any &a, Any &b) { Any temp; temp = a; a = b; b = temp; }

 

4. 重载的模板:

template <class Any> /* 也可以写成 template <typename Any> */ void Swap(Any &a, Any &b) { Any temp; temp = a; a = b; b = temp; } template <class Any> /* 也可以写成 template <typename Any> */ void Swap(Any a[], Any b[], int n) { Any temp; for (int i = 0; i < n; i++) { temp = a[i]; a[i] = b[i]; b[i] = temp; } }

 

  4.1 显示具体化(explicit specialization)  以template<>开头,并通过名称来指出类型  e.g.  struct job {     char name[20];     double salary;     int floor;  };  template<> void Swap<job> (job& a, job &b)  或者可以写成更简单的形式:template<> void Swap(job &a, job &b)

  如果有多个原型,编译器在选择原型时,非模板化版本 > 显示具体化 > 模板版本  // non-template function prototype  void Swap(job &, job &)

  // template prototype  template<typename Any>  void Swap(Any &, Any &)

  // explicit specialization for the job type  template<> void Swap(job &, job &)

  4.2 显示实例化(explicit instantiation)  template void Swap<int> (int, int) (显示具体化声明在template<> 后)  编译器看到上述声明后,将使用Swap()模板生成一个使用int类型的实例。

 

5. using声明 using std::cout;using编译命令 using namespace std;

namespace Jill { double bucket(double n) {...} double fetch; struct Hill {...}; } char fetch; int main() { using namespace Jill; Hill Thrill; /* using Jill::Hill */ double water = bucket(2); /* using Jill::bucket */ double fetch; /* hide Jill::fetch */ cin >> fetch; /* local fetch */ cin >> ::fetch; /* global fetch */ cin >> Jill::fetch; /* Jill::fetch */     return 0; }

 

转载于:https://www.cnblogs.com/xiaokuang/p/4571439.html

最新回复(0)