//MyVector.h
#pragma once
#include<iostream>
using namespace std;
template <typename T>
class MyVector
{
friend ostream&operator<<<T>(ostream&cout, MyVector<T>&obj);
public:
MyVector(int size = 0); //构造函数
MyVector(const MyVector& obj);
~MyVector();
public:
T&operator[](int index);
MyVector&operator= (const MyVector &obj);
int getlen()
{
return m_len;
}
protected:
private:
T *m_space;
int m_len;
};
//MyVector.cpp
#include"MyVector.h"
template<typename T>
MyVector<T>::MyVector(int size = 0)
{
m_len = size;
m_space = new T[m_len];
}
template<typename T>
MyVector<T>::MyVector(const MyVector& obj)
{
if (m_space != NULL)
{
delete[] m_space;
m_space = NULL;
m_len = 0;
}
m_len = obj.m_len;
for (int i = 0; i < m_len; i++)
{
m_space[i] = obj.m_len[i];
}
}
template<typename T>
MyVector<T>::~MyVector()
{
if (m_space != NULL)
{
delete[] m_space;
m_len = 0;
m_space = NULL;
}
}
template<typename T>
T& MyVector<T>::operator[](int index)
{
return m_space[index];
}
template<typename T>
MyVector<T>& MyVector<T>::operator= (const MyVector &obj)
{
if (m_space != NULL)
{
delete[] m_space;
m_space = NULL;
m_len = 0;
}
m_len = obj.m_len;
for (int i = 0; i < m_len; i++)
{
m_space[i] = obj.m_space[i];
}
}
template<typename T>
ostream&operator<<(ostream&cout, MyVector<T>&obj)
{
for (int i = 0; i < obj.getlen(); i++)
{
cout << obj[i]<<" ";
}
cout << endl;
return cout;
}
//main.cpp
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include"MyVector.h"
#include"MyVector.cpp"
using namespace std;
class Teacher
{
public:
Teacher()
{
age = 33;
strcpy(name,"");
}
Teacher(char *name, int age)
{
this->age = age;
strcpy(this->name, name);
}
void print()
{
cout << "age:" << age << " name:" << name << endl;
}
protected:
private:
int age;
char name[32];
};
void main()
{
Teacher t1("a1", 31), t2("a2", 32), t3("a3", 33), t4("a4", 34);
MyVector<Teacher>myv3(4);
myv3[0] = t1;
myv3[1] = t2;
myv3[2] = t3;
myv3[3] = t4;
for (int i = 0; i < myv3.getlen(); i++)// 若要使用cout<<myv3,则需要对Teacher的<<进行重载。
{
Teacher tmp = myv3[i];
tmp.print();
}
}
void main02()
{
MyVector<char>myv2(20);
myv2[0] = 'a';
myv2[1] = 'a';
myv2[2] = 'a';
myv2[3] = 'a';
myv2[4] = 'a';
myv2[5] = 'z';
cout << myv2 << endl;
}
void main01()
{
MyVector<int> myv1(10);
for (int i = 0; i < myv1.getlen(); i++)
{
myv1[i] = i + 1;
cout << myv1[i] << " ";
}
cout << myv1<<endl;
}