Caso de plantilla de clase C ++

1. Caso de plantilla de clase

Descripción del caso: para implementar una clase de matriz general, los requisitos son los siguientes:

  • Puede almacenar datos de tipos de datos integrados y tipos de datos personalizados
  • Almacene los datos en la matriz en el área del montón y use un puntero no especificado de tipo T para apuntar a la matriz dinámica
  • La capacidad de la matriz que se puede pasar se define en el constructor
  • Proporcione el constructor de copia y el operador correspondientes = para evitar problemas de copia superficial
  • Proporcione métodos de interpolación de cola y eliminación de cola para agregar y eliminar datos en la matriz
  • Puede acceder a los elementos de la matriz subindicando
  • Puede obtener el número actual de elementos en la matriz y la capacidad de la matriz

2. Código

#include <iostream>
#include <string>

using namespace std;

class Person
{
    
    
public:

    Person(){
    
    };

    Person(string name, int age)
    {
    
    
        this->m_Name = name;
        this->m_Age = age;
    }

public:
    string m_Name;
    int m_Age;
};


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[this->m_Capacity];

        for(int i=0; i<this->m_Size; i++)
        {
    
    
            this->pAddress[i] = arr.pAddress[i];
        }
    }

    // a = b = c
    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(T val)
    void Push_Back(const T & val)
    {
    
    
        if(this->m_Size !=this->m_Capacity)
        {
    
    
            this->pAddress[this->m_Size] = val;
            this->m_Size += 1;
        }
        else
        {
    
    
            cout << "超出容量" << endl;
            return;
        }
    }

    void Pop_Back()
    {
    
    
        // 让用户访问不到最后一个元素即为尾删
        if(this->m_Size !=0)
        {
    
    
            this->m_Size -= 1;
        }
        else
        {
    
    
            cout << "数组的大小是0" << endl;
            return;
        }
    }

    //arr[0] = 1 
    T& operator[](int index)
    {
    
    
        if(index >= this->m_Size)
        {
    
    
            cout << "越界!" << endl;
            // return;
            //TODO
        }
        else
        {
    
    
            return this->pAddress[index];
        }
        
    }

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

    int getCapacity()
    {
    
    
        return m_Capacity;
    }

    int getSize()
    {
    
    
        return m_Size;
    }

private:
    
    //指针指向堆区开辟的真实数组
    T * pAddress;

    //数组的容量
    int m_Capacity;

    //数组的大小
    int m_Size;

};

void printArray(MyArray<int>& arr)
{
    
    
    cout << "---- start print array ----" << endl;
    for(int i=0; i<arr.getSize(); i++)
    {
    
    
        cout << arr[i] << endl;
    }
    cout << "---- end print array ----" << endl;
}

void printArray(MyArray<Person>& arr)
{
    
    
    cout << "---- start print array ----" << endl;
    for(int i=0; i<arr.getSize(); i++)
    {
    
    
        cout << arr[i].m_Name << "," << arr[i].m_Age << endl;
    }
    cout << "---- end print array ----" << endl;
}

int main(int argc, char** argv)
{
    
    
    MyArray<int>arr1(10);

    // MyArray<int>arr2(arr1);

    // MyArray<int>arr3(100);

    // arr3 = arr1;

    for (int i = 0; i < 5; i++)
    {
    
    
        arr1.Push_Back(i);
    }

    printArray(arr1);

    arr1.Pop_Back();
    
    cout << arr1.getCapacity() << "," << arr1.getSize() << endl;


    MyArray<Person>arr2(3);

    arr2.Push_Back(Person("deng",24));
    arr2.Push_Back(Person("wang",23));
    arr2.Push_Back(Person("meng",25));

    cout << arr2.getCapacity() << "," << arr2.getSize() << endl;

    printArray(arr2);


    return 0;
}

// 自己第一次写的时候出现的问题:
// 1. 有参构造初始化 不知道使用this
// 2. 开辟空间 不知道使用 T * pAddress
// 3. 析构函数 释放数组空间 delete[] 
// 4. 重载运算符 不知道返回 *this

3. Resultados

res

Supongo que te gusta

Origin blog.csdn.net/qq_35632833/article/details/113487207
Recomendado
Clasificación