(文章8) 05章-C++泛型编程(下)

5.4 类模板

5.4.4 类模板对象怎么作为函数参数?

当类模板实例化的对象作为函数参数时,有三种传递方式,核心差异在于"是否让函数感知类模板的类型参数"。

方式 说明 灵活度 推荐度
1. 指定传入类型 void f(Person<string,int>& p) 低 最常用
2. 参数模板化 template<T1,T2> void f(Person<T1,T2>& p) 中 需要通用时使用
3. 整个类模板化 template<T> void f(T& p) 高 仅必要时使用
方式1:指定传入的类型(最常用)

直接显式指定函数参数的类型,如:Person<string, int>&,函数无需模板,逻辑简单。

cpp 复制代码
/*************************************************************************
  > File Name:    demo10.cpp
  > Author:       冯鹏飞
  > Description:  类模板作为函数参数的三种方式
  > Created Time: 2026-11-04 10:31:54
 ************************************************************************/

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

// 类模板
template<class T1, class T2 = int>
class Person
{
private:
    T1 m_Name;
    T2 m_Age;
public:
    Person(T1 name, T2 age) : m_Name(name), m_Age(age){}

    void showInfo()
    {
        cout << "姓名:" << m_Name << ",年龄:" << m_Age << endl;
    }
};

// 方式1:指定传入的类型(最常用),该函数只适用于string+int组合
void printPerson1(Person<string, int>& p)
{
    p.showInfo();
}

int main(int argc,char *argv[])
{
    Person<string, int> p("柳如烟", 500);
    printPerson1(p);
    
    return 0;
}

**注意:**方式1的局限性就在于使用该类型的函数无法实现通用------参数类型已被写死为 Person<string, int>。

方式2:参数模板化(函数模板适配类模板)

将函数参数的类型参数(T1, T2)作为函数模板的类型参数,让函数适配任意类型的类模板对象。

cpp 复制代码
/*************************************************************************
  > File Name:    demo10.cpp
  > Author:       冯鹏飞
  > Description:  类模板作为函数参数的三种方式
  > Created Time: 2026-11-04 10:31:54
 ************************************************************************/

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

// 类模板
template<class T1, class T2 = int>
class Person
{
private:
    T1 m_Name;
    T2 m_Age;
public:
    Person(T1 name, T2 age) : m_Name(name), m_Age(age){}

    void showInfo()
    {
        cout << "姓名:" << m_Name << ",年龄:" << m_Age << endl;
    }
};

// 方式2:参数模板化(函数模板适配类模板)
template<typename T1, typename T2>
void printPerson2(Person<T1,T2>& p)
{
    p.showInfo();
}

int main(int argc,char *argv[])
{
    Person<const char*, int> p2("沈幼楚", 200);
    printPerson2(p2);

    return 0;
}
方式3:整个类模板化(函数模板参数为类模板)

将整个类模板作为函数模板的参数,函数完全不感知类模板的内部类型参数,灵活度最高。

cpp 复制代码
/*************************************************************************
  > File Name:    demo10.cpp
  > Author:       冯鹏飞
  > Description:  类模板作为函数参数的三种方式
  > Created Time: 2026-11-04 10:31:54
 ************************************************************************/

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

// 类模板
template<class T1, class T2 = int>
class Person
{
private:
    T1 m_Name;
    T2 m_Age;
public:
    Person(T1 name, T2 age) : m_Name(name), m_Age(age){}

    void showInfo()
    {
        cout << "姓名:" << m_Name << ",年龄:" << m_Age << endl;
    }
};

template<class T1, class T2 = int>
class Student
{
private:
    T1 m_Name;
    T2 m_Age;
public:
    Student(T1 name, T2 age) : m_Name(name), m_Age(age){}

    void showInfo()
    {
        cout << "姓名:" << m_Name << ",年龄:" << m_Age << endl;
    }
};

// 方式3:整个类模板化(函数模板参数是类模板)
template<typename T>
void printPerson3(T& p)
{
    p.showInfo();
}

int main(int argc,char *argv[])
{
    Person<const char*, string> p3("沈青鸾", "250");
    // printPerson3<Person<const char*, string>>(p3);
    Student<const char*, string> p4("迷彩", "250");
    printPerson3(p3);
    printPerson3(p4);

    return 0;
}

细节点:推荐使用方式1------逻辑简单,可读性高,避免不必要的模板嵌套。

5.4 类模板

5.4.5 类模板怎么继承?【扩展】

当子类继承的父类是模板时,必须显式指定父类的类型参数(或者让子类也成为类模板),否则编译器无法为子类分配内存。

子类继承"已实例化的类模板"(父类类型固定)

若父类的类型参数已确定(如 Base<int>),子类直接继承即可。

cpp 复制代码
/*************************************************************************
  > File Name:    demo11.cpp
  > Author:       冯鹏飞
  > Description:  类模板与继承:子类继承已实例化的类模板(父类类型固定)
  > Created Time: 2026-11-04 10:52:57
 ************************************************************************/

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

// 父类:模板
template<class T>
class Base
{
protected:
    T m_BaseVal;
public:
    Base(T val) : m_BaseVal(val) {}
};

// 子类:继承"已实例化的类模板(模板类)"
// 也就是说:子类继承的其实不是类模板,而是通过类模板生成的模板类
class Son1 : public Base<int>
{
public:
    Son1(int baseVal) : Base<int>(baseVal) {} // Base(..):访问类模板;Base<int>(..):访问模板类

    void showBaseVal()
    {
        cout << "父类成员变量:" << m_BaseVal << endl;
    }
};


int main(int argc,char *argv[])
{
    Son1 s(100);
    s.showBaseVal();

    return 0;
}

运行结果:

shell 复制代码
父类成员变量:100
子类为类模板(父类类型参数由子类指定)

若需父类的成员类型参数灵活配置,子类也需定义为类模板,将父类的类型参数作为子类的模板参数。

cpp 复制代码
/*************************************************************************
  > File Name:    demo11.cpp
  > Author:       冯鹏飞
  > Description:  类模板与继承:子类继承已实例化的类模板(父类类型固定)
  > Created Time: 2026-11-04 10:52:57
 ************************************************************************/

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

// 父类:模板
template<class T>
class Base
{
protected:
    T m_BaseVal;
public:
    Base(T val) : m_BaseVal(val) {}
};

// 子类:继承"已实例化的类模板(模板类)"
// 也就是说:子类继承的其实不是类模板,而是通过类模板生成的模板类
template<class T1, class T2>
class Son2: public Base<T1>
{
private:
    T2 m_SonVal;
public:
    Son2(T2 sonVal, T1 baseVal) : Base<T1>(baseVal), m_SonVal(sonVal) {} // Base(..):访问类模板;Base<int>(..):访问模板类

    void showValue()
    {
        cout << "父类成员变量:" << this->m_BaseVal << endl; // 记住:访问父类T成员,需要加this->
        cout << "子类成员变量:" << this->m_SonVal << endl;
    }
};


int main(int argc,char *argv[])
{
    Son2<string, string> s2("张三", "张三他大");
    s2.showValue();

    Son2<int, int> s3(1001, 1002);
    s3.showValue();
    
    return 0;
}

运行结果:

shell 复制代码
父类成员变量:张三他大
子类成员变量:张三
父类成员变量:1002
子类成员变量:1001

核心规则:父类为类模板时,子类必须明确父类的类型参数(要么固定,要么通过子类模板传递)。
经典 bug :在子类模板中访问父类模板的成员,忘记写 this->。因为父类模板的成员是"依赖名称"(依赖于模板参数),编译器不会自动去父类模板中查找,必须用 this-> 显式告知。同理,也可以用 Base<T2>::m_BaseVal,但 this-> 更简洁。

5.4 类模板

5.4.6 类模板的成员函数怎么在类外实现?【扩展】

若类模板的成员函数在类外实现,需要满足两个关键要求:

  1. 每个成员函数前必须重新声明模板参数(编译器需知道 T 的定义);
  2. 用 类名<模板参数>:: 修饰成员函数(明确属于哪个类模板的实例)。
示例:类模板成员函数类外实现

demo15.h

cpp 复制代码
/*************************************************************************
  > File Name:    demo13.h
  > Author:       冯鹏飞
  > Description:  
  > Created Time: 2026-11-04 11:27:57
 ************************************************************************/

#ifndef _DEMO13_H
#define _DEMO13_H

// 类模板定义
template<class T1, class T2>
class Object
{
private:
    T1 m_Param1;
    T2 m_Param2;
public:
    Object() = default;

    Object(T1 param1, T2 param2);

    void showInfo();
};

#endif //_DEMO13_H

demo15.cpp

cpp 复制代码
/*************************************************************************
  > File Name:    demo13.cpp
  > Author:       冯鹏飞
  > Description:  
  > Created Time: 2026-11-04 11:30:28
 ************************************************************************/

#include <iostream>
#include <string>
#include <iomanip>
#include "demo13.h"

using namespace std;

// 构造函数类外实现
template<typename T1, typename T2> // 注意:类外实现的时候,需要重新声明类模板
Object<T1, T2> :: Object(T1 param1, T2 param2)
{
    this->m_Param1 = param1;
    this->m_Param2 = param2;
}

template<typename T1, typename T2>
void Object<T1, T2> :: showInfo()  
{
    cout << "参数1:" << this->m_Param1 << ",参数2:" << this->m_Param2 << endl;
}

int main(int argc,char *argv[])
{
    Object<string, int> p1("张三", 21);
    Object<string, string> p2("name", "李四");

    p1.showInfo();
    p2.showInfo();

    return 0;
}

运行结果:

shell 复制代码

5.4 类模板

5.4.7 类模板能分文件编写吗?

警示:类模板不能将声明(.h)和实现(.cpp)分开!

原因:类模板的成员函数在调用时才创建,若分文件编写,编译器在链接阶段无法找到成员函数的实现(.cpp 中的模板未实例化),导致"undefined reference"链接错误。
底层原理:普通函数的编译模型是"分离编译"------每个 .cpp 独立编译成 .o,链接器负责拼接。但模板函数在实例化前只是"蓝图"而非真正的代码,.cpp 中的模板定义在单独编译时没有实例化(不知道 T 的具体类型),不产出任何目标代码。等链接阶段需要用到时,已经晚了------找不到函数体。

问题复现(分文件编写报错)
  • demo14.h(声明):

    cpp 复制代码
    /*************************************************************************
      > File Name:    demo14.h
      > Author:       冯鹏飞
      > Description:  
      > Created Time: 2026-11-04 11:27:57
     ************************************************************************/
    
    #ifndef _DEMO13_H
    #define _DEMO13_H
    
    // 类模板定义
    template<class T1, class T2>
    class Object
    {
    private:
        T1 m_Param1;
        T2 m_Param2;
    public:
        Object() = default;
    
        Object(T1 param1, T2 param2);
    
        void showInfo();
    };
    
    #endif //_DEMO13_H
  • demo14.cpp(实现):

    cpp 复制代码
    /*************************************************************************
      > File Name:    demo14.cpp
      > Author:       冯鹏飞
      > Description:  
      > Created Time: 2026-11-04 11:30:28
     ************************************************************************/
    
    #include <iostream>
    #include <string>
    #include <iomanip>
    #include "demo14.h"
    
    using namespace std;
    
    // 构造函数类外实现
    template<typename T1, typename T2> // 注意:类外实现的时候,需要重新声明类模板
    Object<T1, T2> :: Object(T1 param1, T2 param2)
    {
        this->m_Param1 = param1;
        this->m_Param2 = param2;
    }
    
    template<typename T1, typename T2>
    void Object<T1, T2> :: showInfo()  
    {
        cout << "参数1:" << this->m_Param1 << ",参数2:" << this->m_Param2 << endl;
    }
  • main.cpp(调用):

    cpp 复制代码
    /*************************************************************************
      > File Name:    main.cpp
      > Author:       冯鹏飞
      > Description:  
      > Created Time: 2026-11-04 14:11:45
     ************************************************************************/
    
    #include <iostream>
    #include <string>
    #include <iomanip>
    #include "demo14.h"
    
    using namespace std;
    
    int main(int argc,char *argv[])
    {
        Object<string, int> p1("张三", 21);
        Object<string, string> p2("name", "李四");
    
        p1.showInfo();
        p2.showInfo();
    
        return 0;
    }

编译时报错:undefined reference to Person<std::string, int>::Person(std::string, int) 等------因为 demo16.cpp 中的模板代码未被实例化,链接器找不到函数体。

解决方式1:将实现包含到声明文件(不推荐)

在 .h 文件末尾包含 .cpp 文件,让编译器在处理 .h 时同时看到声明和实现:

cpp 复制代码
// demo14.h 末尾添加
#include "demo14.cpp"

// 这个其实就是将所有代码都合并到了main.cpp,编译的时候编译单文件即可

**缺点:**破坏了 .h/.cpp 的分离惯例;若多个 .cpp 文件分别包含该 .h 再编译,会导致同一份模板实现在不同翻译单元中重复,容易引发 ODR(单一定义规则)问题,不符合工程规范。

解决方式2:声明与实现合并为 .hpp 文件(推荐)

将类模板的声明和成员函数实现全部放在一个文件中,后缀名为 .hpp(约定俗成,非强制)。.hpp 文件本质是"模板专用的头文件",兼具声明和实现。

  • demo15.hpp(合并声明与实现)*

    cpp 复制代码
    /*************************************************************************
      > File Name:    demo15.hpp
      > Author:       冯鹏飞
      > Description:  类模板的成员函数类外实现
      > Created Time: 2026-11-04 14:29:18
     ************************************************************************/
    #pragma once    // 防止重复编译
    #include <iostream>
    #include <string>
    #include <iomanip>
    
    // 注意:.hpp作为头文件,不应该使用 using namepace std
    // 类模板定义 ------------------------xxxx.h的代码
    template<class T1, class T2>
    class Object
    {
    private:
        T1 m_Param1;
        T2 m_Param2;
    public:
        Object() = default;
    
        Object(T1 param1, T2 param2);
    
        void showInfo();
    };
    
    // 构造函数类外实现 ------------------xxxx.cpp的代码
    template<typename T1, typename T2> // 注意:类外实现的时候,需要重新声明类模板
    Object<T1, T2> :: Object(T1 param1, T2 param2)
    {
        this->m_Param1 = param1;
        this->m_Param2 = param2;
    }
    
    template<typename T1, typename T2>
    void Object<T1, T2> :: showInfo()  
    {
        std::cout << "参数1:" << this->m_Param1 << ",参数2:" << this->m_Param2 << std::endl;
    }
  • main.cpp(调用)

    cpp 复制代码
    /*************************************************************************
      > File Name:    main.cpp
      > Author:       冯鹏飞
      > Description:  
      > Created Time: 2026-11-04 14:11:45
     ************************************************************************/
    
    #include <iostream>
    #include <string>
    #include <iomanip>
    #include "demo15.hpp"
    
    using namespace std;
    
    int main(int argc,char *argv[])
    {
        Object<string, int> p1("张三", 21);
        Object<string, string> p2("name", "李四");
    
        p1.showInfo();
        p2.showInfo();
    
        return 0;
    }
  • g++编译命令:

    bash 复制代码
    g++ main.cpp -o demo15 -std=c++11 -Wall
    # -std=c++11:指定使用 C++11 标准(也可以用 -std=c++14/-std=c++17,更高版本兼容)
    # -Wall:开启所有常用警告,帮助发现潜在代码问题

细节点 :.hpp 命名约定------.hpp 专用于模板(声明+实现在一个文件),.h + .cpp 用于普通类。这帮助开发者一眼识别哪些是模板代码。

5.4 类模板

5.4.8 类模板怎么声明友元?

友元函数可访问类的私有成员,类模板的友元需要区分"全局函数类内实现 "和"全局函数类外实现",核心是让编译器提前感知函数的存在。

全局函数类内实现

直接在类模板内声明并实现友元函数,编译器可直接识别,无需额外处理。

cpp 复制代码
/*************************************************************************
  > File Name:    demo16.cpp
  > Author:       冯鹏飞
  > Description:  类模板与友元:全局函数类内实现
  > Created Time: 2026-11-04 14:42:23
 ************************************************************************/

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

template<class T1, class T2>
class Person
{
    // 友元函数:全局函数的类内实现
    // 注意:使用friend修饰的函数,哪怕在类内部实现,它也是全局函数
    friend void printPerson(Person<T1,T2>& p)
    {
        cout << "姓名:" << p.m_Name << ",年龄:" << p.m_Age << endl;
    }
private:
    T1 m_Name;
    T2 m_Age;
public:
    Person() = default; // 显示声明默认无参构造

    Person(T1 name, T2 age) : m_Name(name), m_Age(age){}

};

int main(int argc,char *argv[])
{
    Person<string, int> p("吕小布", 19);

    // 访问全局函数
    printPerson(p);
    
    return 0;
}

运行结果:

shell 复制代码
姓名:吕小布,年龄:19
全局函数类外实现

若友元函数在类外实现,需满足三个步骤:

  1. 提前声明类模板(让编译器知道 Person<T1, T2> 是类模板);
  2. 提前声明友元函数模板(让编译器知道函数的存在);
  3. 类内声明友元时加 <>(表示是模板函数)。

经典 bug :类外实现友元函数模板时,忘记在类内 friend 声明后加 <>。不加 <> 编译器会认为你声明的是一个普通非模板函数,链接时找不到匹配的函数体。"<> 相当于告诉编译器:我声明的是那个已经提前声明的模板函数,请把它们关联起来。"

cpp 复制代码
/*************************************************************************
  > File Name:    demo17.cpp
  > Author:       冯鹏飞
  > Description:  类模板与友元:全局函数的类外实现
  > Created Time: 2026-11-04 14:50:23
 ************************************************************************/

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

// 步骤1:提前声明类模板
template <class T1, class T2>
class Person;

// 步骤2:提前声明友元函数模板
template <typename T1, typename T2>
void printPerson(Person<T1, T2> &p);

// 类模板定义
template <class T1, class T2>
class Person
{
    // 友元函数:全局函数的类外实现
    // 注意:类内声明,类外实现,需要添加<> 表示是模板函数
    friend void printPerson<>(Person<T1, T2> &p);

private:
    T1 m_Name;
    T2 m_Age;

public:
    Person() = default; // 显示声明默认无参构造

    Person(T1 name, T2 age) : m_Name(name), m_Age(age) {}
};

// 步骤3:友函数模板的类外实现
template <typename T1, typename T2>
void printPerson(Person<T1, T2> &p)
{
    cout << "姓名:" << p.m_Name << ",年龄:" << p.m_Age << endl;
}

int main(int argc, char *argv[])
{
    Person<string, int> p("吕小布", 19);

    // 访问全局函数
    printPerson(p);
    return 0;
}

运行结果:

shell 复制代码
姓名:吕小布,年龄:19

5.4 类模板

5.4.9 综合案例:手写一个通用数组类 MyVector

需求:实现一个通用数组类(容器),支持:

  1. 存储内置类型(int、double)和自定义类型(如 Person);
  2. 堆区存储数据(避免栈溢出);
  3. 核心功能:尾插、尾删、下标访问、获取容量/大小;
  4. 避免浅拷贝(实现拷贝构造和 operator=)。

这是本章最重要的综合案例,涵盖了类模板的所有核心知识点。

实现代码

Vector.hpp

cpp 复制代码
/*************************************************************************
  > File Name:    Vector.hpp
  > Author:       冯鹏飞
  > Description:  自定义通用数组类
  > Created Time: 2026-11-04 15:22:34
 ************************************************************************/
#pragma once // 添加头文件保护(防止重复编译)
#include <iostream>
#include <string>
#include <iomanip>
#include <stdexcept> // 用于抛出异常

template <class T>
class MyVector
{
private:
    T *data;      // 堆区数组指针
    int capacity; // 数组容量
    int size;     // 当前元素的个数

    // 私有扩容函数:容量满时自动扩充为原来的2倍
    void expand()
    {
        // 获得新扩容容量 = 原容量 * 2
        int new_capacity = this->capacity * 2;
        T *new_data = new T[new_capacity]; // 在堆区申请新的内存
        // 拷贝原有元素
        for (int i = 0; i < this->size; i++)
            new_data[i] = this->data[i]; // 从原空间取数据存入到新空间
        // 释放旧内存
        delete[] this->data;
        // 更新指针和容量
        this->data = new_data;
        this->capacity = new_capacity;
    }

public:
    // 构造函数:校验容量合法性
    MyVector(int capacity = 10)
    {
        // 校验容量:负数或0默认设为10
        this->capacity = (capacity > 0) ? capacity : 10;
        this->size = 0;
        this->data = new T[this->capacity];
    }

    // 深拷贝构造函数
    MyVector(const MyVector &other)
    {
        this->capacity = other.capacity;
        this->size = other.size;
        this->data = new T[this->capacity]; // 将other的堆上数据拷贝到自己的堆空间
        for (int i = 0; i < this->size; i++)
            this->data[i] = other.data[i];
    }

    // 深拷贝运算符重载
    MyVector &operator=(const MyVector &other)
    {
        if (this == &other)
            return *this; // 防止自赋值

        // 释放当前对象的堆内存
        if (this->data != nullptr)
            delete[] this->data;

        // 深拷贝
        this->capacity = other.capacity;
        this->size = other.size;
        this->data = new T[this->capacity];
        for (int i = 0; i < this->size; i++)
            this->data[i] = other.data[i];

        return *this;
    }

    // 尾插法:添加自动扩容
    void pushBack(const T &val)
    {
        // 容量已满则自动扩容
        if (this->size >= this->capacity)
            this->expand(); // 扩容
        this->data[this->size++] = val;
    }

    // 尾删法:调用元素析构函数
    void popBack()
    {
        if (this->size == 0)
        {
            std::cout << "数组为空,无法尾删!" << std::endl;
            return;
        }
        // 显示调用被删除元素的析构函数
        this->data[this->size - 1].~T(); // 最后一个元素的下标 = this->size - 1
        this->size--;
    }

    // 清空数组
    void clear()
    {
        // 调用所有元素的析构函数
        for (int i = 0; i < this->size; i++)
            this->data[i].~T();
        this->size = 0;
    }

    // 判断数组是否为空
    bool empty() const
    {
        return this->size == 0;
    }

    // 获取容量
    int getCapacity() const
    {
        return this->capacity;
    }

    // 获取元素个数
    int getSize() const
    {
        return this->size;
    }

    // 重载[]运算符(非const版本) 支持修改数据
    T &operator[](const int index)
    {
        return this->data[index]; // MyVector<int> numbers;   numbers[0];
    }

    // 重载[]运算符(const版本)   仅遍历数据
    const T &operator[](const int index) const
    {
        return this->data[index];
    }

    // at函数(非const版本,抛出异常处理越界),因为[]访问无法处理越界,所以提供更为安全的访问at
    T &at(const int index)
    {
        // 越界抛出异常
        if (index < 0 || index >= this->size)
        {
            throw std::out_of_range("下标越界:index = " + std::to_string(index) + ",size = " + std::to_string(this->size));
        }
        return this->data[index];
    }

    // at函数(const版本,抛出异常处理越界),因为[]访问无法处理越界,所以提供更为安全的访问at
    const T &at(const int index) const
    {
        // 越界抛出异常
        if (index < 0 || index >= this->size)
        {
            throw std::out_of_range("下标越界:index = " + std::to_string(index) + ",size = " + std::to_string(this->size));
        }
        return this->data[index];
    }

    // 析构函数
    ~MyVector()
    {
        if (this->data != nullptr)
        {
            // 先调用所有元素的析构函数
            for (int i = 0; i < this->size; i++)
                this->data[i].~T(); // 比如,我们存储Student类型的对象,这里就是在释放对象中的堆成员
            // 再释放数组内存
            delete[] this->data;
            this->data = nullptr;
        }
    }
};

// class Student
// {
//     private:
//         std::string *name;
//     public:

//         ~Student()
//         {
//             if (name != nullptr) delete name;
//         }
// };

// MyVector<Student> stus;

Main.cpp

cpp 复制代码
/*************************************************************************
  > File Name:    main.cpp
  > Author:       冯鹏飞
  > Description:
  > Created Time: 2026-11-04 16:19:27
 ************************************************************************/

#include <iostream>
#include <string>
#include <iomanip>
#include "Vector.hpp"

using namespace std;

void test1()
{
    // 创建容器
    MyVector<int> arr(5); // 容量为5的int数组

    // 尾插(超过容量会自动扩容)
    for (int i = 0; i < 7; i++)
    {
        arr.pushBack(i + 10); // 10,11,12,13,14,15,16
    }

    cout << "数组容量:" << arr.getCapacity() << endl; // 10
    cout << "元素个数:" << arr.getSize() << endl;     // 7

    // 下标访问
    cout << "数组元素(下标访问):";
    for (int i = 0; i < arr.getSize(); i++)
        cout << arr[i] << " ";
    cout << endl;

    // 尾删
    arr.popBack();
    cout << "尾删后元素个数:" << arr.getSize() << endl; // 6

    // 拷贝构造
    MyVector<int> arr2(arr);
    cout << "拷贝构造数组元素:";
    for (int i = 0; i < arr2.getSize(); i++)
        cout << arr2[i] << " ";
    cout << endl;

    // 测试clear()
    arr2.clear();
    cout << "clear后数组是否为空:" << boolalpha << arr2.empty() << endl; // boolalpha 显示的时候,1-true,0-false
}

// 测试2:自定义类型
class Person
{
public:
    Person() = default;
    Person(string name, int age) : m_Name(name), m_Age(age) {}

    void showInfo() const
    {
        cout << "姓名:" << m_Name << ",年龄:" << m_Age << endl;
    }

private:
    string m_Name;
    int m_Age;
};

void test2()
{
    MyVector<Person> arr(3);

    // 为插法
    Person p1("刘备", 21), p2("关羽", 20), p3("张飞", 19);
    arr.pushBack(p1);
    arr.pushBack(p2);
    arr.pushBack(p3);

    // 遍历数组
    cout << "\nPerson数组遍历:" << endl;
    for (int i = 0; i < arr.getSize(); i++)
        arr[i].showInfo();

    // 拷贝构造
    MyVector<Person> arr2(arr);
    // 运算符重载
    arr2 = arr;
    cout << "赋值后Person数组元素:" << endl;
    for (int i = 0; i < arr2.getSize(); i++)
        arr2[i].showInfo();
}

int main(int argc, char *argv[])
{
    test1();
    cout << endl;
    test2();
    return 0;
}

运行结果:

shell 复制代码
数组容量:10
元素个数:7
数组元素(下标访问):10 11 12 13 14 15 16 
尾删后元素个数:6
拷贝构造数组元素:10 11 12 13 14 15 
clear后数组是否为空:true


Person数组遍历:
姓名:刘备,年龄:21
姓名:关羽,年龄:20
姓名:张飞,年龄:19
赋值后Person数组元素:
姓名:刘备,年龄:21
姓名:关羽,年龄:20
姓名:张飞,年龄:19

配对铁律 :new[] 必须配 delete[],构造时必须 new 分配堆内存,析构时必须 delete[] 归还。MyVector 的析构函数中,还要先逐一调用元素的析构函数(this->data[i].~T()),再释放数组内存------特别是当 T 是自定义类时,不调析构函数会导致成员变量(如 string)的内部堆内存泄漏。
面试考点:面试官大概率会问"你的 MyVector 和 std::vector 有什么区别?"------std::vector 是工业级实现,考虑了内存分配器(Allocator)、迭代器、异常安全保证(strong exception guarantee)、SSO 优化等。不过手写 MyVector 展示了你理解类模板的核心机制:深拷贝、扩容策略、RAII 资源管理、移动语义 ------ 这些才是面试官想看到的。


5.5 模板核心总结

  1. **泛型编程是思想,模板是实现:**模板通过"虚拟类型"封装通用逻辑,解决"逻辑相同、类型不同"的重复代码问题;
  2. 函数模板关键点:
    • 实例化方式:隐式(自动推导)、显式(手动指定);
    • 与普通函数区别:隐式转换支持不同,调用时优先普通函数;
    • 局限性:需通过"模板具体化"适配自定义类型;
  3. 类模板关键点:
    • 仅支持显式实例化,类型参数可设默认值(C++17 起支持 CTAD 隐式实例化);
    • 成员函数用到时才创建,分文件需用 .hpp 合并声明与实现;
    • 继承时需明确父类类型参数,友元需提前声明;
  4. **实际应用:**模板是 STL 的基础(如 vector、list 等容器均为类模板),日常开发更多是使用 STL 而非手动编写复杂模板,但需理解模板的核心逻辑以灵活使用 STL。

下一章预告 :第6章将学习 STL(标准模板库)------基于模板技术实现的六大组件(容器、迭代器、算法、仿函数、适配器、分配器)。STL 提供了开箱即用的数据结构(vector/list/map/set 等)和算法(sort/find/for_each 等),将大幅提升你的开发效率。

相关推荐
回眸&啤酒鸭1 小时前
【回眸】AI 大模型驱动 Tessy 单元测试集成效果全景展示
网络·人工智能·单元测试
赵文宇(温玉)3 小时前
Docker离线安装
运维·docker·容器
进击的荆棘3 小时前
Linux网络——传输层协议UDP
linux·运维·服务器·网络·udp
Android系统攻城狮4 小时前
FFmpeg深度解析之av_bsf_get_by_name:如何查找码流过滤器?(七十九)
linux·运维·ffmpeg·音视频进阶·ffmpeg音视频
Decay__5 小时前
PostgreSQL 监控体系构建 —— postgres_exporter + Prometheus + Grafana 全栈实战
运维·数据库·sql·postgresql
ShineWinsu6 小时前
对于Qt:TCP的解析
linux·c++·qt·网络协议·面试·tcp·客户端
Decay__7 小时前
PostgreSQL 告警与自动化运维 —— 告警分级收敛、Webhook、定时巡检、脚本库
运维·数据库·sql·postgresql
笔记本note7 小时前
Linux GPIO 技术详解
linux·gpio
东坡大表哥8 小时前
【Ubuntu】Ubuntu 20.04 LTS → 22.04 LTS 升级实录
android·linux·ubuntu