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


    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; }
  • 相关阅读:
    Redis与Redis 伪集群环境的搭建
    github的基本使用
    使用七牛云存储图片或文件并回显
    阿里云搭建wordpress博客教程
    判断是否同一天 同一月
    Python学习笔记之 并发编程
    Python学习笔记之 日志模块logging使用详解
    Python学习笔记之 网络编程(socket套接字编程)
    Python实现TCP文件传输
    实例:Python实现聊天室
  • 原文地址:https://www.cnblogs.com/xiaokuang/p/4571439.html
Copyright © 2020-2023  润新知