C++(四十四) — 数组模板类(vector工具)

  实现 stl 中的 vector 操作。

1、MyVector.h

#pragma once

#include <iostream>
using namespace std;

template <typename T>
class MyVector
{
    friend ostream& operator<< <T>(ostream &out, MyVector<T> &obj);
public:
    MyVector(int size = 0);//构造函数
    MyVector(const MyVector &obj);//拷贝构造函数
    ~MyVector();//析构函数

    T& operator[] (int index);
    MyVector &operator=(const MyVector &obj);
    

    int getLen() {
        return m_len;
    }
protected:
    T *m_space;
    T m_len;
};

 

2、MyVector.cpp

#include <iostream>
using namespace std;
#include "MyVector.h"

template <typename T>
MyVector<T>::MyVector(int size = 0)  //构造函数
{
    m_space = new T[size];
    m_len = size;
}
template <typename T>
MyVector<T>::MyVector(const MyVector &obj)//拷贝构造函数
{
    m_len = obj.m_len;
    m_space = new T[m_len];

    for (int i = 0; i < m_len; i++)
    {
        m_space[i] = obj.m_space[i];
    }
}
template <typename T>
MyVector<T>::~MyVector()//析构函数
{
    if (m_space != nullptr)
    {
        delete[] m_space;
        m_space = nullptr;
        m_len = 0;
    }
}
//ostream& operator<< <T>(ostream &out, MyVector<T> &obj)
template <typename T>
ostream& operator<< (ostream &out,  MyVector<T> &obj)
{
    for (int i = 0; i < obj.m_len; i++)
    {
        out << obj.m_space[i] << "  ";
    }
    out << endl;
    return out;
}


template <typename T>
T& MyVector<T>::operator[] (int index)
{
    return m_space[index];
}

template <typename T>
MyVector<T> & MyVector<T>::operator=(const MyVector<T> &obj)
{
    if (m_space != nullptr)
    {
        delete[] m_space;
        m_space = nullptr;
        m_len = 0;
    }
    m_len = obj.m_len;
    m_space = new T[m_len];
    for (int i = 0; i < m_len; i++)
    {
        m_space[i] = obj[i];
    }

    return *this;
}

 

3、MyVector.cpp(测试函数)

#include <iostream>
using namespace std;
#include "MyVector.cpp"

void main()
{
    MyVector<int> mv1(10);
    for (int i = 0; i < mv1.getLen(); i++)
    {
        mv1[i] = i + 1;
        cout << mv1[i] << endl;
    }
    cout << endl;

    MyVector<int> mv2 = mv1;
    for (int i = 0; i < mv2.getLen(); i++)
    {
        mv2[i] = i + 1;
    }
    cout << mv2 << endl;
    

    system("pause");

}

 

posted @ 2019-06-04 22:32  深度机器学习  阅读(515)  评论(0编辑  收藏  举报