C++中的模板

本阶段主要针对C++泛型编程和STL技术做详细讲解,探讨C++更深层的使用

1. 模板

1.1. 模板的概念

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

模板的特点:

  1. 通用型很强,但只是一个框架,不能直接使用
  2. 模板并不是万能的

例如生活中的模板:

  • 一寸照片模板

  • PPT模板

1.2. 函数模板

  • C++另一种编程思想称为泛型编程,主要利用的技术就是模板
  • C++提供两种模板机制:函数模板和类模板

1.2.1. 函数模板语法

函数模板的作用:建立一个通用函数,其函数返回值类型和形参类型可以不具体绑定,用一个虚拟的类型来代表。

语法:

template<typename T>
函数声明或定义

解释:

  • template:声明创建模板
  • typename:表示其后面的符号是一种数据类型,可以用class代替
  • T:通用的数据类型,名称可以替换,通常为大写字母

示例:

#include<iostream>
using namespace std;

//函数模板
//实现两个整型交换的函数
void swap_int(int &a, int &b)
{
    int temp = a;
    a = b;
    b = temp;
}

//实现两个浮点型交换的函数
void swap_double(double &a, double &b)
{
    double temp = a;
    a = b;
    b = temp;
}

//函数模板
template<typename T>  //声明一个模板,告诉编译器,下面代码中的T是一个通用数据类型,不要报错
void my_swap(T &a, T &b)
{
    T temp = a;
    a = b;
    b = temp;
}


int main()
{
    int a = 10;
    int b = 20;
    // swap_int(a, b);

    //利用函数模板实现交换
    //1、自动类型推导(编译器自己推理T是什么类型)
    // my_swap(a, b);
    
    //2、显式指定类型
    my_swap<int>(a, b);

    cout << "a = " << a << endl;
    cout << "b = " << b << endl;

    double c = 11.5462;
    double d = 22.4512;
    swap_double(c, d);

    cout << "c = " << c << endl;
    cout << "d = " << d << endl;

    return 0;
}


输出:
---------------------------------------------------------------------------------
a = 20
b = 10
c = 22.4512
d = 11.5462

1.2.2. 函数模板注意事项

注意事项:

  • 自动类型推导时,必须推导出一致的数据类型T,才可以使用
  • 模板必须要确定出T的数据类型,才可以使用

示例:

#include<iostream>
using namespace std;

//函数模板
template<typename T>  //typename可以换成class
void my_swap(T &a, T &b)
{
    T temp = a;
    a = b;
    b = temp;
}

//1、自动类型推导时,必须推导出一致的数据类型T,才可以使用
void test01()
{
    int a = 10;
    int b = 20;
    char c = 'c';

    my_swap(a, b);  //正确
    // my_swap(a, c);  //错误!编译器不能推导出一致的数据类型T

    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
}

//2、模板必须要确定出T的数据类型,即使模板函数中没有用到T这个数据类型,也需要指定才可以使用
template<typename T>
void func()
{
    cout << "func 函数调用" << endl;
}

void test02()
{
    //func();  //错误!编译器无法推导数据类型。必须给出T的数据类型,才可以使用
    func<int>();  //正确
}


int main()
{
    test01();
    test02();

    return 0;
}


输出:
---------------------------------------------------------------------------------
a = 20
b = 10
func 函数调用

1.2.3. 函数模板案例-数组排序

案例描述:

  • 利用函数模板封装一个排序函数,可以对不同数据类型数组进行排序
  • 排序规则从大到小,排序算法为选择排序
  • 分别利用char数组和int数组进行测试

示例:

#include<iostream>
using namespace std;

//交换函数模板
template<typename T>
void MySwap(T &a, T &b)
{
    T temp = a;
    a = b;
    b = temp;
}

//排序算法模板
template<typename 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++)
        {
            if (arr[max] < arr[j])
            {
                max = j;
            }
        }

        if (max != i)
        {
            MySwap(arr[i], arr[max]);
        }
    }
}

//打印数组模板
template<typename T>
void PrintArray(T arr[], int len)
{
    for (int i = 0; i < len; i++)
    {
        cout << arr[i] << " ";
    }
    cout << endl;
}

//测试char数组
void Test01()
{
    char char_array[] = "badcfe";
    int len = sizeof(char_array) / sizeof(char);

    MySort(char_array, len);
    PrintArray(char_array, len);
}

//测试int数组
void Test02()
{
    int int_array[] = {1, 5, 3, 2, 4};
    int len = sizeof(int_array) / sizeof(int);

    MySort(int_array, len);
    PrintArray(int_array, len);
}

int main()
{
    Test01();
    Test02();

    return 0;
}


输出:
---------------------------------------------------------------------------------
f e d c b a  
5 4 3 2 1 

1.2.4. 普通函数与模板函数的区别

  • 普通函数调用时可以发生自动类型转换(隐式类型转换)
  • 函数模板调用时,如果利用自动类型推导,不会发生隐式类型转换
  • 显式指定类型T时,可以发生隐式类型转换

示例:

#include<iostream>
using namespace std;

// 普通函数与模板函数的区别

//普通函数
int SimAdd(int a, int b)
{
    return a + b;
}

//函数模板
template<class T>
T TemAdd(T a, T b)
{
    return a + b;
}


void Test01()
{
    int a = 10;
    int b = 20;
    char c = 'c';  //ASCII码:a-97 c-99

    // 1、普通函数调用时可以发生自动类型转换(隐式类型转换)
    cout << SimAdd(a, c) << endl;

    // 2、函数模板调用时,如果利用自动类型推导,不会发生隐式类型转换
    // cout << TemAdd(a, c) << endl;

    // 3、显式指定类型T时,可以发生隐式类型转换
    cout << TemAdd<int>(a, c) << endl;
    cout << TemAdd<char>(a, c) << endl;
}

int main()
{
    Test01();
    // Test02();

    return 0;
}


输出:
---------------------------------------------------------------------------------
109
109
m

总结:建议使用显式指定类型的方式调用函数模板,因为可以自己确定通用类型T,避免编译器报错

1.2.5. 普通函数和函数模板的调用规则

  1. 如果函数模板和普通函数都可以实现,优先调用普通函数(如果普通函数只有声明,没有实现,程序在链接阶段报错)
  2. 可以通过空模板参数列表来强制调用函数模板
  3. 函数模板也可以发生重载
  4. 如果函数模板可以产生更好的匹配,优先调用函数模板

示例:

#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;
    int b = 20;

    MyPrint(a, b);

    // 通过空模板参数列表来强制调用函数模板
    MyPrint<>(a, b);

    // 函数模板也可以发生重载
    MyPrint(a, b, 100);

    // 如果函数模板可以产生更好的匹配,优先调用函数模板
    char c = 'a';
    char d = 'b';
    MyPrint(c, d);
}

int main()
{
    Test01();
    // Test02();

    return 0;
}


输出:
---------------------------------------------------------------------------------
调用的普通函数
调用的模板函数
调用重载的模板函数
调用的模板函数

总结:在已经提供函数模板的情况下,最好不要提供普通函数,否则容易出现二义性

1.2.6. 模板的局限性

模板的通用性并不是万能的

例如:

template<class T>
void f(T a, T b)
{
    a = b;
}

上述代码提供赋值操作,但如果传入的参数a,b是一个数组,就无法实现

再例如:

template<class T>
void f(T a, T b)
{
    if(a > b){...}
}

上述代码中,如果T的数据类型是自定义数据类型(类似Person),就无法正常运行

C++为了解决诸如此类的问题,提供了模板重载,可以为特定的类型提供具体化的模板

示例:

#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 &v1, T &v2)
{
    if(v1 == v2)
    {
        return true;
    }
    else
    {
        return false;
    }
}

//利用具体化的Person版本实现模板对比函数
template<>bool MyCompare(Person &v1, Person &v2)
{
    if(v1.m_name == v2.m_name && v1.m_age == v2.m_age)
    {
        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", 15);
    Person p2("Tom", 15);

    bool ret = MyCompare(p1, p2);
    
    if (ret)
    {
        cout << "p1 == p2" << endl;
    }
    else
    {
        cout << "p1 != p2" << endl;
    }
}

int main()
{
    Test01();
    Test02();

    return 0;
}


输出:
---------------------------------------------------------------------------------
a != b
p1 == p2

总结:

  • 利用具体化模板,可以解决自定义类的通用化(模板化)
  • 学习模板并不是为了写模板,而是为了在STL中能够运用系统提供的模板

1.3. 类模板

1.3.1. 类模板语法

类模板的作用:

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

语法:

template<typename T>
类

解释:

template:声明创建模板

typename:表明其后面的符号是一种数据类型,可以用class代替

T:通用的数据类型,名称可以替换,通常为大写字母

示例:

#include<iostream>
using namespace std;

// 类模板
template<class NameType, class AgeType>
class Person
{
public:

    Person(NameType name, AgeType age)
    {
        this->m_name = name;
        this->m_age = age; 
    }

    void ShowPerson()
    {
        cout << this->m_name << " " << this->m_age << endl;
    }

    NameType m_name;
    AgeType m_age;
};

void Test01()
{
    Person<string, int> p1("孙悟空", 999);
    p1.ShowPerson();
}

int main()
{
    Test01();

    return 0;
}


输出:
---------------------------------------------------------------------------------
孙悟空 999

总结:类模板和函数模板语法相似,在声明模板template后面加类,此类称为类模板

1.3.2. 类模板与函数模板的区别

  1. 类模板没有自动类型推导的使用方式
  2. 类模板在模板参数列表中可以有默认参数

示例:

#include<iostream>
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 << " age = " << this->m_age << endl;
    }

    NameType m_name;
    AgeType m_age;
};

// 1. 类模板没有自动类型推导的使用方式
void Test01()
{
    // Person p("孙悟空", 999); // 报错
    Person<string, int> p1("孙悟空", 999);
    p1.ShowPerson();
}

// 2. 类模板在模板参数列表中可以有默认参数
void Test02()
{
    Person<string> p2("猪八戒", 666);
    p2.ShowPerson();
}


int main()
{
    Test01();
    Test02();

    return 0;
}

输出:
---------------------------------------------------------------------------------
name = 孙悟空 age = 999
name = 猪八戒 age = 666

1.3.3. 类模板中成员函数的创建时机

类模板中成员函数和普通类中成员函数创建时机是有区别的:

  • 普通类中的成员函数一开始就可以创建
  • 类模板中的成员函数在调用时才能创建

示例:

#include<iostream>
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:

    T obj;

    void func1()
    {
        obj.ShowPerson1();
    }

    void func2()
    {
        obj.ShowPerson2();
    }
};


void Test01()
{
    MyClass<Person1> m;
    m.func1();

    MyClass<Person2> n;
    n.func2();
}

// void Test02()
// {
//     Person<string> p2("猪八戒", 666);
//     p2.ShowPerson();
// }


int main()
{
    Test01();
    // Test02();

    return 0;
}


输出:
---------------------------------------------------------------------------------
Person1 Show
Person2 Show

1.3.4. 类模板对象做函数参数

学习目标:

  • 类模板实例化出的对象,向函数传参的方式

一共有三种传参方式:

  1. 指定传入的类型 --- 直接显示对象的数据类型(最常用)
  2. 参数模板化 --- 将对象中的参数变为模板进行传递
  3. 整个类模板化 --- 将这个对象类型模板化进行传递

示例:

#include<iostream>
using namespace std;

// 类模板对象做函数参数
template<class T1, class T2>
class Person
{
public:

    Person(T1 name, T2 age)
    {
        this->m_Name = name;
        this->m_Age = age;
    }

    void ShowPerson()
    {
        cout << "name: " << this->m_Name << " age: " << 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();

    return 0;
}


输出:
---------------------------------------------------------------------------------
name: 孙悟空 age: 100
name: 猪八戒 age: 90
T1的类型为:NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
T2的类型为:i
name: 唐僧 age: 30
T的类型为:6PersonINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEiE

总结:

  • 通过类模板创建的对象,可以有三种方式向函数中进行传参
  • 使用比较广泛的是第一种:指定传入类型

1.3.5. 类模板与继承

当类模板遇到继承时,需要注意以下几点:

  • 当子类继承的父类是一个类模板时,子类在声明的时候,要指定出父类中的T的类型
  • 如果不指定,编译器无法给子类分配内存
  • 如果想灵活指定出父类中T的类型,子类也需要变为模板

示例:

#include<iostream>
using namespace std;

// 类模板与继承

// ● 当子类继承的父类是一个类模板时,子类在声明的时候,要指定出父类中的T的类型
// ● 如果不指定,编译器无法给子类分配内存

template<class T>
class Base
{
public:

    T m;
};

// class Son : public Base  //报错,必须要知道父类中T的类型,才能继承给子类,否则编译器不知道分配多少内存给子类
class Son : public Base<int>
{

};

void Test01()
{
    Son s1;
}

// ● 如果想灵活指定出父类中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 Test02()
{
    Son2<int, char> s2;
}

int main()
{
    Test01();
    Test02();

    return 0;
}


输出:
---------------------------------------------------------------------------------
T1的类型为:int
T2的类型为:char

总结:如果父类是类模板,子类需要指定出父类中T的数据类型

1.3.6. 类模板成员函数类外实现

学习目标:掌握类模板中的成员函数类外实现

示例:

#include<iostream>
using namespace std;

// 类模板成员函数类外实现
template<class T1, class T2>
class Person
{
public:
    Person(T1 name, T2 age);
    // {
    //     this->m_Name = name;
    //     this->m_Age = age;
    // }

    void showPerson();
    // {
    //     cout << "姓名: " << this->m_Name << " 年龄: " << this->m_Age << endl;
    // }

    T1 m_Name;
    T2 m_Age;
};

//构造函数类外实现
template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age)
{
    this->m_Name = name;
    this->m_Age = age;
}

//成员函数的类外实现
template<class T1, class T2>
void Person<T1, T2>::showPerson()
{
    cout << "姓名: " << this->m_Name << " 年龄: " << this->m_Age << endl;
}

void Test01()
{
    Person<string, int> p("Tom", 20);
    p.showPerson();
}

int main()
{
    Test01();

    return 0;
}


输出:
---------------------------------------------------------------------------------
姓名: Tom 年龄: 20

总结:类模板中成员函数类外实现时,需要加上模板参数列表template<class T1, class T2><T1, T2>

1.3.7. 类模板分文件编写

学习目标:

  • 掌握类模板成员函数分文件编写产生的问题以及解决方式

问题:

  • 类模板中成员函数创建时机是在调用阶段,导致分文件编写时链接不到

解决:

  • 解决方式1:直接包含.cpp源文件
  • 解决方式2:将声明和实现写到同一个文件中,并更改后缀名为.hpp.hpp是约定俗成的名称,并非强制要求(主流解决方案)

解决方式1中直接包含.cpp而不是.h文件的原因是:类模板中的成员函数的创建时间是在函数被调用的阶段,在.h文件的声明过程中没有创建,在.cpp文件中调用时才创建,这就会导致编译器通过#include"XXX.h"文件链接不到类模板中的成员函数

示例:

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)
{
    this->m_Name = name;
    this->m_Age = age;
}

//成员函数的类外实现
template<class T1, class T2>
void Person<T1, T2>::showPerson()
{
    cout << "姓名: " << this->m_Name << " 年龄: " << this->m_Age << endl;
}

类模板分文件编写.cpp中的代码:

#include<iostream>
using namespace std;

// 解决方式1:直接包含.cpp源文件
// #include"person.cpp"

// 解决方式2:将声明和实现写到同一个文件中,并更改后缀名为.hpp,.hpp是约定俗成的名称,并非强制要求
#include"person.hpp"

void Test01()
{
    Person<string, int> p("Jerry", 18);
    p.showPerson();
}

int main()
{
    Test01();

    return 0;
}

1.3.8. 类模板与友元

学习目标:

  • 掌握类模板配合友元函数的类内和类外实现

全局函数类内实现:直接在类内声明友元即可

全局函数类外实现:需要提前让编译器知道全局函数的存在

示例:

#include<iostream>
using namespace std;

//通过全局函数,打印Person信息

//提前让编译器知道带函数模板的Person类的存在
template<class T1, class T2>
class Person;

//2、全局函数在类外实现
template<class T1, class T2>
void PrintPerson2(Person<T1, T2> P2)
{
    cout << "类外实现 -- 姓名:" << P2.m_Name << " 年龄:" << P2.m_Age << endl;
}

template<class T1, class T2>
class Person
{
    //全局函数,类内实现
    friend void PrintPerson(Person<T1, T2> P)
    {
        cout << "类内实现 -- 姓名:" << P.m_Name << " 年龄:" << 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;
};

//1、全局函数在类内实现
void Test01()
{
    Person<string, int> P("孙悟空", 1000);
    PrintPerson(P);
}


void Test02()
{
    Person<string, int> P2("猪八戒", 2000);
    PrintPerson2(P2);
}

int main()
{
    Test01();
    Test02();

    return 0;
}


输出:
---------------------------------------------------------------------------------
类内实现 -- 姓名:孙悟空 年龄:1000
类外实现 -- 姓名:猪八戒 年龄:2000

总结:建议全局函数做类内实现,用法简单,而且编译器可以直接识别

1.3.9. 类模板案例-数组类封装

案例描述:实现一个通用的数组类,要求如下:

  • 可以对内置数据类型以及自定义数据类型的数据进行存储
  • 将数组中的数据存储到堆区
  • 构造函数中可以传入数组的容量
  • 提供对应的拷贝构造函数以及operator=防止浅拷贝问题
  • 提供尾插法和尾删法对数组中的数据进行增加和删除
  • 可以通过下标的方式访问数组中的元素
  • 可以获取数组中当前元素个数和数组容量

示例:

MyArray.hpp

//写一个属于我的通用数组类
#pragma once
#include <iostream>
using namespace std;

template<class T>
class MyArray
{
public:

    //有参构造函数,传递数组中的参数容量
    MyArray(int capacity)
    {
        cout << "有参构造函数调用" << endl;

        this->m_capacity = capacity;
        this->m_size = 0;
        this->p_address = new T[this->m_capacity];
    }

    //拷贝构造函数(防止浅拷贝问题)
    MyArray(const MyArray & arr)
    {
        cout << "拷贝构造函数调用" << endl;

        this->m_capacity = arr.m_capacity;
        this->m_size = arr.m_size;
        // this->p_address = arr.p_address;  //默认的拷贝构造函数会生成此浅拷贝

        //深拷贝
        this->p_address = new T[this->m_capacity];
        
        //将arr数组中已有的数据拷贝到自己开辟的数组中
        for(int i = 0; i < this->m_size; i++)
        {
            this->p_address[i] = arr.p_address[i];
        }
    }

    //重载赋值运算符(防止浅拷贝问题)
    MyArray & operator=(const MyArray & arr)
    {
        cout << "调用了重载赋值运算符函数" << endl;

        //先判断原来堆区是否有数据,如果有,先释放掉
        if(this->p_address != NULL)
        {
            delete [] this->p_address;
            this->p_address = NULL;
            this->m_capacity = 0;
            this->m_size = 0;
        }
        

        //深拷贝,重新申请堆区空间
        this->m_capacity = arr.m_capacity;
        this->m_size = arr.m_size;
        this->p_address = new T[this->m_capacity];

        for(int i = 0; i < this->m_size; i++)
        {
            this->p_address[i] = arr.p_address[i];
        }
        return *this;
    }

    //尾插法
    void PushBack(const T & val)
    {
        //判断容量是否满了
        if(this->m_size == this->m_capacity)
        {
            cout << "容量满了" << endl;
            return;        
        }

        this->p_address[this->m_size] = val;  //在数组末尾插入数据
        this->m_size++;   //更新数组大小
    }

    //尾删法
    void PopBack()
    {
        //让用户访问不到数组的最后一个元素,即为尾删(逻辑删除)
        if(this->m_size == 0)
        {
            cout << "数组为空" << endl;
            return;
        }

        this->m_size--;  //更新数组大小
    }

    //重载中括号运算符,让用户通过下标访问数组中的元素
    T & operator[](int index)
    {
        return this->p_address[index];
    }

    //获取数组容量
    int GetCapacity()
    {
        return this->m_capacity;
    }

    //获取数组大小
    int GetSize()
    {
        return this->m_size;
    }

    //析构函数
    ~MyArray()
    {
        if(this->p_address != NULL)
        {
            cout << "析构函数调用" << endl;

            delete [] this->p_address;
            this->p_address = NULL;
        }

    }
    
private:

    T * p_address;  //指针指向堆区开辟的真实数组
    int m_capacity; //数组容量
    int m_size;     //数组中有效数据的个数
};

类模板案例-数组类封装.cpp

#include<iostream>
using namespace std;
#include"MyArray.hpp"

void PrintIntArray(MyArray<int>& arr)
{
    for (int i = 0; i < arr.GetSize(); i++)
    {
        //测试重载的中括号索引
        cout << arr[i] << " ";
    }

    cout << endl;
}

void Test01()
{
    MyArray<int> arr1(10);

    for(int i = 0; i < 5; i++)
    {
        //利用尾插法向数组中插入数据
        arr1.PushBack(i);
    }

    cout << "arr1的打印输出为:" << endl;

    PrintIntArray(arr1);

    cout << "arr1的容量为:" << arr1.GetCapacity() << endl;
    cout << "arr1的元素个数为:" << arr1.GetSize() << endl;

    cout << "----------------------------" << endl;
    MyArray<int> arr2(arr1);

    cout << "arr2的打印输出为:" << endl;

    //利用尾删法删除数组中的数据
    arr2.PopBack();

    cout << "arr2尾删后:" << endl;
    cout << "arr2的容量为:" << arr2.GetCapacity() << endl;
    cout << "arr2的元素个数为:" << arr2.GetSize() << endl;

    PrintIntArray(arr2);

    cout << "----------------------------" << endl;
    MyArray<int> arr3(100);
    
    arr3 = arr1;  //调用重载赋值运算符函数
}

//测试自定义数据类型
class Person
{
public:
    //在C++中,如果定义了任何构造函数,除非明确告知,否则编译器不会生成默认构造函数。
    //数组初始化:创建对象数组时,需要使用默认构造函数初始化数组中的每个元素。
    //由于 MyArray<T> 使用动态数组分配(new T[this->m_capacity]),它依赖于T的默认构造函数的存在。
    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 << " 年龄:" << arr[i].m_age << endl;
    }
}

void Test02()
{
    MyArray<Person> arr(20);

    Person p1("孙悟空", 1000);
    Person p2("猪八戒", 900);
    Person p3("沙和尚", 800);
    Person p4("唐僧", 700);
    Person p5("鲁智深", 600);

    //将数据插入到数组中
    arr.PushBack(p1);
    arr.PushBack(p2);
    arr.PushBack(p3);
    arr.PushBack(p4);
    arr.PushBack(p5);

    //打印数组
    PrintPersonArray(arr);

    //输出容量
    cout << "容量:" << arr.GetCapacity() << endl;

    //输出大小
    cout << "大小:" << arr.GetSize() << endl;
}

int main()
{
    Test01();
    Test02();

    return 0;
}

测试输出:

有参构造函数调用
arr1的打印输出为:
0 1 2 3 4 
arr1的容量为:10
arr1的元素个数为:5
----------------------------
拷贝构造函数调用
arr2的打印输出为:
arr2尾删后:
arr2的容量为:10
arr2的元素个数为:4
0 1 2 3 
----------------------------
有参构造函数调用
调用了重载赋值运算符函数
析构函数调用
析构函数调用
析构函数调用
有参构造函数调用
姓名:孙悟空 年龄:1000
姓名:猪八戒 年龄:900
姓名:沙和尚 年龄:800
姓名:唐僧 年龄:700
姓名:鲁智深 年龄:600
容量:20
大小:5
析构函数调用

1.3.10. 悬挂指针问题

悬挂指针问题(也称为野指针问题)是编程中一个常见的错误,尤其是在使用底层语言如C或C++时,这种错误的后果可能是严重的。悬挂指针指的是指向一块已经被释放或无效内存的指针。这类问题的发生往往因为对内存管理的处理不当。

1.3.10.1. 悬挂指针的产生

悬挂指针问题(也称为野指针问题)是编程中一个常见的错误,尤其是在使用底层语言如C或C++时,这种错误的后果可能是严重的。悬挂指针指的是指向一块已经被释放或无效内存的指针。这类问题的发生往往因为对内存管理的处理不当。

1.3.10.1. 悬挂指针的产生

悬挂指针问题可以由以下几种情况产生:

1. 释放后使用:

当一块内存被释放(例如通过delete或free)之后,任何仍然指向那块内存的指针都会变成悬挂指针。如果程序之后尝试使用这样的指针(读取或写入操作),就会导致未定义行为,如访问违规或数据损坏。

2. 作用域外使用:

当指针指向一个局部变量,而该局部变量的作用域已经结束时,该指针也会成为悬挂指针。因为局部变量在其作用域结束时会被销毁,其占用的内存可能被其他数据覆盖。

3. 复制后删除:

如果两个指针指向同一块内存,当其中一个指针被用来释放那块内存后,另一个指针仍然指向那个地址,这时第二个指针就变成了悬挂指针。

1.3.10.2. 悬挂指针的危险性

悬挂指针的使用可能导致多种类型的错误和安全隐患,包括:

  • 程序崩溃:试图访问已释放的内存可能会导致访问违规错误,引起程序崩溃。

  • 数据损坏:如果悬挂指针被用来修改已释放的内存,这可能会覆盖和损坏程序中的其他数据。

  • 安全漏洞:攻击者可能利用悬挂指针漏洞来注入和执行恶意代码,尤其是在系统软件或网络服务中。

1.3.10.3. 避免悬挂指针

为了避免悬挂指针的问题,可以采用以下几种策略:

  1. 及时清空指针:

  • 在释放指针指向的内存后,立即将指针设为NULL(或在C++中为nullptr)。这样,指针就不再指向之前的内存地址,即使它被错误地使用也不会导致悬挂指针问题。

2. 使用智能指针:

  • 在C++中,使用智能指针(如std::unique_ptr和std::shared_ptr)可以自动管理内存。这些智能指针在销毁时会自动释放它们所拥有的内存,避免了悬挂指针的产生。

3. 避免多重删除:

  • 确保每块动态分配的内存只被释放一次。在释放内存后,确认没有其他指针仍指向该内存。

4. 谨慎管理指针和资源:

  • 在设计软件时,对资源的生命周期和所有权保持清晰的认识,谨慎管理指针和其他资源的使用。

通过采取这些措施,可以大大降低悬挂指针问题的风险,提高程序的稳定性和安全性。

  • 32
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值