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");

}

 

转载于:https://www.cnblogs.com/eilearn/p/10976684.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值