1.4 KiB
Raw Blame History

2.11 容器和模板

2.11.1 标准容器

Vector

List

Map

Set

2.11.2 迭代器

2.11.3 模板类

使用模板的目的就是能够让程序员编写与类型无关的代码。比如编写了一个交换两个整型int 类型的swap函数这个函数就只能实现int 型对double字符这些类型无法实现要实现这些类型的交换就要重新编写另一个swap函数。使用模板的目的就是要让这程序的实现与类型无关比如一个swap模板函数即可以实现int 型又可以实现double型的交换。

模板的声明或定义只能在全局,命名空间或类范围内进行。

函数模板的格式为:

template<class 形参名, class 形参名, ...> 返回类型 函数名(参数列表)
{
    ...
}

类模板的格式为:

template<class 形参名, class 形参名, ...> class 类名
{
    ...
};

一个简单的示例如下:

/**
 * @file    ATemplate.h
 */
#pragma once        // 只被编译一次.

template<class T> class A{
public:
    A();
    T Add(T a,T b);
};

#endif
/**
 * @file    ATemplate.cpp
 */
#include "ATemplate.h"
#include <iostream.h>

template<class T> A<T>::A()
{
}

template<class T> T A<T>::Add(T a,T b)
{
    return a+b;
}
/**
 * @file    main.cpp
 */
#include "ATemplate.h"

void main(){
    A<int> a;
    cout<<a.Add(2, 3)<<endl;
}

练习

基于模板实现堆栈操作。