各位大牛帮忙看看问题出来哪?自己实现一个数组模板类,编译无法通过

大家帮忙查查问题出在哪?
目的:自己实现一个数组模板类,并重载+、=、[]、<<等运算符,并完成对int、char及自定义类型的实现。
现在初期就遇到问题,研究了一天了,硬是没有找到解决方法,跪求!!

VS2010问题提示如下:

d:\c-demo\数组类模板\数组类模板\myvector.cpp(41): error C2678: 二进制“[”: 没有找到接受`“const MyVector <T>`类型的左操作数的运算符(或没有可接受的转换)
//////////////////////////////////////////////////////////////////////
//代码清单1 MyVector.h
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;

template <typename T>
class MyVector
{
    friend ostream& operator<< <T> (ostream& out, MyVector<T> &obj);
public:
    MyVector(int len = 0);
    MyVector(const MyVector &obj);
    ~MyVector();
public:
    MyVector& operator=(const MyVector &obj);
    MyVector& operator+(const MyVector &obj);
    T& operator[](int index);
public:
    int getLen()
    {
        return m_len;
    }
protected:
private:
    T *m_space;
    T m_len;
};

/////////////////////////////////////////////////////////////////////////
//代码清单2 MyVector.cpp
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include "MyVector.h"
using namespace std;

template <typename T>
ostream& operator<<(ostream& out, MyVector<T> &obj)
{
    for (int i = 0; i < obj.m_len;i++)
    {
        out<<obj.m_space[i]<<"  ";
    }
    return out;
}

template <typename T>
MyVector<T>::MyVector(int len)
{
    m_len = len;
    m_space = new T[m_len];
}

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


template <typename T>
MyVector<T>::~MyVector()
{
    if (m_space !=NULL)
    {
        delete[] m_space;
        m_space = NULL;
        m_len = 0;
    }
}

template <typename T>
MyVector<T>& MyVector<T>::operator=(const MyVector<T> &obj)
{
    if (m_space !=NULL)
    {
        delete[] m_space;
        m_space = NULL;
        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;
}

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

/////////////////////////////////////////////////////////////////////////
//代码清单3 MyVector_Test.cpp
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
//#include "MyVector.h"
#include "MyVector.cpp"
using namespace std;

void main()
{
    MyVector<int> v1(5);
    for (int i = 0;i < v1.getLen();i++)
    {
        v1[i] = i;
        cout<<v1[i]<<"  ";
    }
    cout<<endl;
    MyVector<int> v2 = v1;
    cout<<v2<<endl;

    cout<<"hello..."<<endl;
    system("pause");
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值