C++学习 --- 模板

1、模板的概念

模板就是建立通用的模具,大大提高复用性。

生活中的模板:

一寸照模板

PPT模板:框架美观,填充“肉”即可。等。

模板通用性很强,不可以直接使用,只是一个框架。

模板并不是万能的。

2、函数模板
2.1、函数模板语法

#include <iostream>
using namespace std;
​
//函数模板 
//声明一个模板,告诉编译器后面代码中紧跟的T不要报错,T是通用的数据类型
 template<typename T>void mySwap(T &a, T &b) {
     T temp = a;
     a = b;
     b = temp;
 }
​
​
//两个整形交换的函数
void swapInt(int &a, int &b) {
    int temp = a;
    a = b;
    b = temp;
}
​
//交换两个浮点型的函数
void swapDouble(double &a, double &b) {
    double temp = a;
    a = b;
    b = temp;
}
​
void test01() {
    int a = 10;
    int b = 20;
    /*swapInt(a,b);
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    double c = 1.1;
    double d = 2.2;
    swapDouble(c, d);
    cout << "c = " << c << endl;
    cout << "d = " << d << endl;*/
    
    //利用函数模板来交换
    //两种方式来使用模板
    //1.自动类型推导
    mySwap(a,b);
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    
    //2.显示指定类型
    mySwap<int>(a, b);
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
}
​
int main() {
    test01();
    system("pause");
    return 0;
}

2.2、函数模板注意事项

#include <iostream>
using namespace std;
​
//函数模板注意事项
//1、自动类型推导,必须推导出一致的数据类型T才可以使用
template<typename T>  //typename 可以替换成class
void mySwap(T &a, T &b) {
    T temp = a;
    a = b;
    b = temp;
}
​
void test01() {
    int a = 10;
    int b = 20;
    char c = 'c';
    //正确
    mySwap(a, b);
    //错误,推导不出一致的T类型
    //mySwap(a, c);
​
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
}
​
//2、模板必须要确定出T的数据类型,才可以使用
template <class T>
void func() {
    cout << "func 调用" << endl;
}
​
void test02() {
    func<int>();   //显示指出这个T是int,否则无法调用该函数  
}
​
​
int main() {
    test01();
    test02();
​
    system("pause");
    return 0;
}
2.3、函数模板案例

#include <iostream>
using namespace std;
​
//实现通用 对数组进行排序的函数
//规则 从大到小
//算法 选择
//测试 char 数组 、int 数组
//交换函数模板
template<class T>
void mySwap(T &a, T &b) {
    T temp = a;
    a = b;
    b = temp;
}
​
//排序算法模板,选择排序
template<class T>
void mySort(T arr[],int len) {
    for (int i = 0; i < len; i++) {
        //认定最大值的下标
        int max = i;
        for (int j = i + 1; j < len; j++) {
            //认定的最大值比遍历出的数值要小,说明j下标的元素才是真正的最大值
            if (arr[max] < arr[j]) {
                //更新最大值下标
                max = j;
            }
        }
        if (max != i) {
            //交换max 和 i 下标元素
            mySwap(arr[i],arr[max]);
        }
    }
}
​
//打印数组模板
template<class T>
void printArray(T arr[], int len) {
    for (int i = 0; i < len; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}
​
void test01() {
    //测试char数组
    char charArr[] = "aebfcd";
    int num = sizeof(charArr) / sizeof(char);
    mySort(charArr, num);
    printArray(charArr,num);
}
​
void test02() {
    //测试char数组
    int intArr[] = {7,2,3,6,5,8,10};
    int num = sizeof(intArr) / sizeof(int);
    mySort(intArr, num);
    printArray(intArr, num);
}
​
int main() {
    test01();
    test02();
​
    system("pause");
    return 0;
}
2.4、普通函数与函数模板的区别

#include <iostream>
using namespace std;
​
//普通函数与函数模板的区别
//1、普通函数调用可以发生隐式类型转换的
//2、函数模板 用自动类型推导,不可以发生隐式类型转换
//3、函数模板 用显示指定类型,可以发生隐式类型转换
//普通函数
int myAdd01(int a,int b) {
    return a + b;
}
​
template<class T>
T myAdd02(T a, T b) {
    return a + b;
}
​
void test01() {
    int a = 10;
    int b = 20;
    char c = 'c';  // 'c'-->99
    cout << myAdd01(a, c) << endl;
​
    //自动类型推导,不可以发生隐式类型转换
    //cout << myAdd02(a, c) << endl;
//显示指定类型,可以发生隐式类型转换
    cout << myAdd02<int>(a, c) << endl;
}
​
​
int main() {
    test01();
​
    system("pause");
    return 0;
}

总结:建议使用显示指定类型的方式,调用函数模板,因为可以自己确定通用类型T

2.5、普通函数与函数模板的调用规则

#include <iostream>
using namespace std;
​
//普通函数与函数模板的调用规则
//1、如果函数模板和普通函数都可以调用,优先调用普通函数
//2、可以通过空模板参数列表 强制调用 函数模板
//3、函数模板也可以发生函数重载
//4、如果函数模板可以产生更好的匹配,优先调用函数模板
void myPrint(int a, int b) {
    cout << "调用的是普通函数" << endl;
}
​
template<class T>
void myPrint(T a, T b) {
    cout << "调用的是函数模板" << endl;
}
​
template<class T>
void myPrint(T a, T b,T c) {
    cout << "调用的是重载函数模板" << endl;
}
​
void test01() {
    int a = 10, b = 20;
    //优先调用普通函数
    //myPrint(a,b);
//通过空模板参数列表 强制调用 函数模板
    //myPrint<>(a, b);
    
    //函数模板也可以发生函数重载
    //myPrint(a,b,100);
//如果函数模板可以产生更好的匹配,优先调用函数模板
    char c1 = 'a';
    char c2 = 'b';
    myPrint(c1,c2);
}
​
int main() {
    test01();
​
    system("pause");
    return 0;
}

2.6、模板的局限性

#include <iostream>
using namespace std;
​
//模板的局限性
//模板并不是万能的,有些特定数据类型,需要具体化方式做特殊实现
class Person {
public:
    Person(string name, int age) {
        this->m_Name = name;
        this->m_Age = age;
    }
​
    //姓名
    string m_Name;
    //年龄
    int m_Age;
};
​
//对比两个数据是否相等
template<class T>
bool myCompare(T &a, T &b) {
    if (a == b) {  //解决方法1:运算符重载
        return true;
    }
    else {
        return false;
    }
}
​
//解决方法2:提供Person类型的重载版本,优先调用
template<> bool myCompare(Person &p1, Person &p2) {
    if (p1.m_Name == p2.m_Name && p1.m_Age == p2.m_Age) {  //解决方法1:运算符重载
        return true;
    }
    else {
        return false;
    }
}
​
void test01() {
    int a = 10;
    int b = 20;
    bool ret = myCompare(a,b);
    if (ret) {
        cout << "a == b" << endl;
    }
    else
    {
        cout << "a != b" << endl;
    }
}
​
void test02() {
    Person p1("Tom", 10);
    Person p2("Tom", 11);
​
    bool ret = myCompare(p1,p2);
    if (ret) {
        cout << "p1 == p2" << endl;
    }
    else {
        cout << "p1 != p2" << endl;
    }
}
​
int main() {
    test01();
    test02();
​
    system("pause");
    return 0;
}

3、类模板
3.1、类模板语法

类模板的作用:

建立一个通用类,类中的成员数据类型可以不具体制定,用一个虚拟的类型来代表。

#include <iostream>
#include <string>
using namespace std;
​
//类模板 class后面是通用数据类型
template<class NameType,class AgeType>
class Person {
public:
    Person(NameType name, AgeType age) {
        this->m_Name = name;
        this->m_Age = age;
    }
​
    void showPerson() {
        cout << "name:" << this->m_Name << "\t"
            << "age:" << this->m_Age << endl;
    }
​
    NameType m_Name;
    AgeType m_Age;
};
​
void test01() {
    //类型参数化 Person<string, int> 模板参数列表
    Person<string, int> p1("孙悟空",999);
    p1.showPerson();
}
​
int main() {
    test01();   
​
    system("pause");
    return 0;
}

3.2、类模板与函数模板区别

#include <iostream>
#include <string>
using namespace std;
​
//类模板与函数模板区别
template<class NameType,class AgeType = int>
class Person {
public:
    Person(NameType name, AgeType age) {
        this->m_Name = name;
        this->m_Age = age;
    }
​
    void showPerson() {
        cout << "name:" << this->m_Name << "\t"
            << "age:" << this->m_Age << endl;
    }
​
    NameType m_Name;
    AgeType m_Age;
};
​
//1.类模板没有自动类型推导使用方式
void test01() {
    //无法用自动类型推导
    //Person p("孙悟空", 1000);
​
    Person<string, int> p1("孙悟空",999);
    p1.showPerson();
}
​
//2.类模板在模板参数列表中可以有默认参数
//template<class NameType,class AgeType = int>
void test02() {
    Person<string> p("猪八戒",200);
    p.showPerson();
}
​
int main() {
    test01();   
    test02();   
​
    system("pause");
    return 0;
}
3.3、类模板中成员函数创建时机

#include <iostream>
#include <string>
using namespace std;
​
//类模板中成员函数创建时机
//类模板中成员函数在调用时才去创建
class Person1 {
public:
    void showPerson1() {
        cout << "Person1 show" << endl;
    }
};
​
class Person2 {
public:
    void showPerson2() {
        cout << "Person2 show" << endl;
    }
};
​
template<class T>
class MyClass {
public:
    //类模板中的成员函数
    void func1() {
        obj.showPerson1();
    }
​
    void func2() {
        obj.showPerson2();
    }
    //以上两个成员函数在调用时候才去创建
    T obj;
};
​
void test01() {
    //MyClass<Person1> m;
    MyClass<Person2> m;
    //m.func1();
    m.func2();
}
​
int main() {
    test01();   
​
    system("pause");
    return 0;
}
3.4、类模板对象做函数参数

#include <iostream>
#include <string>
using namespace std;
​
//类模板的对象做函数参数
template<class T1,class T2>
class Person {
public:
    Person(T1 name, T2 age):m_Name(name), m_Age(age) {}
​
    void showPerson(){
        cout << "姓名:" << this->m_Name << "\t"
            << "年龄:" << this->m_Age << endl;
    }
    T1 m_Name;
    T2 m_Age;
};
​
//1、指定传入类型
void printPerson1(Person<string, int> &p) {
    p.showPerson();
}
void test01() {
    Person<string, int> p("孙悟空", 100);
    printPerson1(p);
}
​
//2、参数模板化
template<class T1,class T2>
void printPerson2(Person<T1, T2> &p) {
    p.showPerson();
    cout << "T1的类型为:" << typeid(T1).name() << endl;
    cout << "T2的类型为:" << typeid(T2).name() << endl;
}
void test02() {
    Person<string, int> p("猪八戒", 90);
    printPerson2(p);
}
​
//3、整个类模板化
template<class T>
void printPerson3(T &p) {
    p.showPerson();
    cout << "T 的数据类型:" << typeid(T).name() << endl;
}
void test03() {
    Person<string, int> p("唐僧", 30);
    printPerson3(p);
}
​
int main() {
    test01();   
    test02();   
    test03();   
​
    system("pause");
    return 0;
}

3.5、类模板与继承

#include <iostream>
#include <string>
using namespace std;
​
//类模板与继承
template<class T>
class Base {
    T m;
};
​
//错误,必须要知道父类中的T类型,才能继承给子类
//class Son :public Base {
//正确
class Son :public Base<int> {
};
​
//如果像灵活之类父类中T类型,子类也需要变类模板
template<class T1,class T2>
class Son2 :public Base<T2> {
public:
    Son2() {
        cout << "T1的类型为:" << typeid(T1).name() << endl;
        cout << "T2的类型为:" << typeid(T2).name() << endl;
    }
    T1 obj;
};
​
void test01() {
    Son s1;
}
​
void test02() {
    //父类中的T是char,自身的是int
    Son2<int, char> S2;
}
​
int main() {
    test01();   
    test02();   
​
    system("pause");
    return 0;
}

3.6、类模板成员函数类外实现

#include <iostream>
#include <string>
using namespace std;
​
//类模板成员函数类外实现
template<class T1,class T2>
class Person {
public:
    Person(T1 name, T2 age);
    void showPerson();
​
    T1 m_Name;
    T2 m_Age;
};
​
//构造函数的类外实现
template<class T1,class T2>
Person<T1,T2>::Person(T1 name, T2 age):m_Name(name),m_Age(age){}
​
//成员函数的类外实现
template<class T1,class T2>
void Person<T1,T2>::showPerson() {
    cout << "姓名:" << this->m_Name << "\t"
        << "年龄:" << this->m_Age << endl;
}
​
void test01() {
    Person<string, int> P("Tom", 20);
    P.showPerson();
}
​
int main() {
    test01();   
​
    system("pause");
    return 0;
}

3.7、类模板分文件编写

//类模板分文件编写.cpp  
//问题提出:当做分文件编写时,出现无法解析外部命令,类模板成员函数创建时机是在调用阶段
//第一种解决方式直接包含源文件,一般不用
//#include "person.cpp"
//第二种解决方式,将.h .cpp 中的内容写在一起,将后缀名改为.hpp,一看就知道是类模板
#include "person.hpp"void test01() {
    Person<string, int> p("Jerry", 18);
    p.showPerson();
}
​
int main() {
    test01();   
​
    system("pause");
    return 0;
}
//person.hpp
#pragma once
​
#include <iostream>
#include <string>
using namespace std;
​
template<class T1, class T2 >
class Person {
public:
    Person(T1 name, T2 age);
    void showPerson();
​
    T1 m_Name;
    T2 m_Age;
};
​
template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age) :m_Name(name), m_Age(age) {}
​
template<class T1, class T2>
void Person<T1, T2>::showPerson() {
    cout << "姓名:" << this->m_Name << "\t"
        << "年龄:" << this->m_Age << endl;
}

3.8、类模板与友元

#include <iostream>
#include <string>
using namespace std;
​
//类外实现
//提前知道person 类
template<class T1,class T2>
class Person;
​
//提前知道函数模板
template<class T1, class T2> //让编译器知道T1,T2存在
void printPerson2(Person<T1, T2> p) {
    cout << "类外实现: " << endl;
    cout << "姓名:" << p.m_Name << "\t"
        << "年龄:" << p.m_Age << endl;
}
​
//通过全局函数打印Person的信息
template<class T1,class T2>
class Person {
    //全局函数 类内实现
    friend void printPerson(Person<T1, T2> p) {
        cout << "姓名:" << p.m_Name << "\t"
            << "年龄:" << p.m_Age << endl;
    }
​
    //全局函数类外实现
    //加空模板的参数列表
    //若全局函数是类外实现,需要让编译器知道这个函数的存在
    friend void printPerson2<>(Person<T1, T2> p);
public:
    Person(T1 name, T2 age) {
        this->m_Name = name;
        this->m_Age = age;
    }
​
private:
    T1 m_Name;
    T2 m_Age;
};
​
​
//全局函数在类内实现的测试
void test01() {
    Person<string, int> p("Tom", 20);
    printPerson(p);
}
​
//全局函数在类外实现的测试
void test02() {
    Person<string, int> p("Jerry", 21);
    printPerson2(p);
}
​
int main() {
    test01();   
    test02();   
​
    system("pause");
    return 0;
}

3.9、类模板案例

//MyArray.hpp
#pragma once
​
#include <iostream>
#include <string>
using namespace std;
​
//自己的通用数组类
template<class T>
class MyArray {
public:
    //有参构造 参数 容量
    MyArray(int capacity) {
        cout << "MyArray 有参构造调用!" << endl;
        this->m_Capacity = capacity;
        this->m_Size = 0;
        this->pAddress = new T[this->m_Capacity];
    }
​
    //拷贝构造函数
    MyArray(const MyArray & arr) {
        cout << "MyArray 拷贝构造调用!" << endl;
        this->m_Capacity = arr.m_Capacity;
        this->m_Size = arr.m_Size;
        //this->pAddress = arr.pAddress; //浅拷贝
        
        //深拷贝
        this->pAddress = new T[arr.m_Capacity];
        //将arr中的数据都拷贝过来
        for (int i = 0; i < this->m_Size; i++) {
            this->pAddress[i] = arr.pAddress[i];
        }
    }
​
    //operator= 防止浅拷贝问题 
    //返回引用  用于连等的情况
    MyArray& operator=(const MyArray & arr) {
        cout << "MyArray operator=调用!" << endl;
        //先判断原来堆区是否有数据,如果有先释放
        if (this->pAddress != NULL) {
            delete[]  this->pAddress;
            this->pAddress = NULL;
            this->m_Capacity = 0;
            this->m_Size = 0;
        }
        //深拷贝
        this->m_Capacity = arr.m_Capacity;
        this->m_Size = arr.m_Size;
        this->pAddress = new T[this->m_Capacity];
        for (int i = 0; i < this->m_Size; i++) {
            this->pAddress[i] = arr.pAddress[i];
        }
        return *this;
    }
    
    //尾插法
    void Push_Back(const T &val) {
        //先判断容量是否已经等于大小
        if (this->m_Capacity == this->m_Size) {
            return;
        }
        //在数组的末尾插入数据
        this->pAddress[this->m_Size] = val;
        //更新数组大小
        this->m_Size++;
    }
​
    //尾删法
    void Pop_Back() {
        //用户访问不到最后一个元素,即为尾删法,逻辑删除
        if (this->m_Size == 0) {
            return;
        }
        this->m_Size--;
    }
​
    //通过下标方式访问数组中的元素
    //若返回作为左值存在,需要用引用的方式返回
    T & operator[](int index) {
        return this->pAddress[index];
    }
​
    //返回数组的容量
    int getCapacity() {
        return this->m_Capacity;
    }
​
    //返回数组的大小
    int getSize() {
        return this->m_Size;
    }
​
    //析构函数
    ~MyArray() {
        if (this->pAddress != NULL) {
            cout << "MyArray 析构调用!" << endl;
delete[] this->pAddress;
this->pAddress = NULL;
    }
    }
private:
T * pAddress;  //指针指向堆区开辟的真实数组
int m_Capacity;//数组容量
int m_Size;    //数组大小
​
};
//MyArrayTest.cpp
​
#include <iostream>
#include <string>
#include "MyArray.hpp"
using namespace std;
​
void printIntArray(MyArray<int> &arr) {
    for (int i = 0; i < arr.getSize(); i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}
​
void test01() {
    MyArray<int> arr1(5);
    for (int i = 0; i < 5; i++) {
        //尾插法插入数据
        arr1.Push_Back(i);
    }
    cout << "arr1 的打印输出为:" << endl;
    printIntArray(arr1);
    cout << "arr1 的容量为:" << arr1.getCapacity() << endl;
    cout << "arr1 的大小为:" << arr1.getSize() << endl;
​
    MyArray<int> arr2(arr1);
    cout << "arr2 的打印输出为:" << endl;
    printIntArray(arr2);
​
    //尾删法
    arr2.Pop_Back();
    cout << "arr2 的尾删后为:" << endl;
    printIntArray(arr2);
    cout << "arr2 的容量为:" << arr2.getCapacity() << endl;
    cout << "arr2 的大小为:" << arr2.getSize() << endl;
​
    MyArray<int> arr3(100);
    arr3 = arr1;
}
​
//测试自定义数据类型
class Person {
public:
    Person() {};
    Person(string name,int age) {
        this->m_Name = name;
        this->m_Age = age;
    }
    string m_Name;
    int m_Age;
};
​
void printPersonArray(MyArray<Person> &arr) {
    for (int i = 0; i < arr.getSize(); i++) {   
        cout << "姓名:" << arr[i].m_Name << "\t"
            << "年龄:" << arr[i].m_Age << endl;   
    }
}
​
void test02() {
    MyArray<Person> arr(10);
    Person p1("孙悟空",999);
    Person p2("韩信",23);
    Person p3("妲己",24);
    Person p4("赵云",21);
    Person p5("安其拉",22);
    //将数据插入到数组中
    arr.Push_Back(p1);
    arr.Push_Back(p2);
    arr.Push_Back(p3);
    arr.Push_Back(p4);
    arr.Push_Back(p5);
    //打印
    printPersonArray(arr);
    cout << "arr 的容量:" << arr.getCapacity() << endl;
    cout << "arr 的大小:" << arr.getSize() << endl;
}
​
int main() {
    test01();   
    test02();
​
    system("pause");
    return 0;
}
​
/*
​
MyArray 有参构造调用!
arr1 的打印输出为:
0 1 2 3 4
arr1 的容量为:5
arr1 的大小为:5
MyArray 拷贝构造调用!
arr2 的打印输出为:
0 1 2 3 4
arr2 的尾删后为:
0 1 2 3
arr2 的容量为:5
arr2 的大小为:4
MyArray 有参构造调用!
MyArray operator=调用!
MyArray 析构调用!
MyArray 析构调用!
MyArray 析构调用!
MyArray 有参构造调用!
姓名:孙悟空    年龄:999
姓名:韩信      年龄:23
姓名:妲己      年龄:24
姓名:赵云      年龄:21
姓名:安其拉    年龄:22
arr 的容量:10
arr 的大小:5
MyArray 析构调用!
请按任意键继续. . .
​
*/
posted @ 2021-08-30 21:35  yiwenzhang  阅读(46)  评论(0编辑  收藏  举报