实现非常简单的数组模板类(MyVector)中用到了泛型编程(模板类编程)、运算符重载、友元函数等知识,最重要的是加深了对内存分配的理解。
所有容器提供的都是值(value)语意,而非引用(reference)语意。容器执行插入元素的操作时,内部实施拷贝动作。所以STL容器内存储的元素必须能够被拷贝(必须提供拷贝构造函数)。
开始的时候不理解这句话,然后自己敲代码就理解了。我们在往容器里存数据的时候,是进行拷贝动作,也就是说将外部变量的值拷贝给容器中的值。要进行拷贝就必须分配内存,没有分配内存的话往哪拷数据呢????而基础数据类型的变量是不用担心这些问题的,因为当我们写下int a
时编译器已经为a
分配了内存,但是如果是指针变量就必须考虑深拷贝与浅拷贝的问题(其实这个地方第一次的时候我想的是,MyVector不是已经分配了内存了吗,为什么还要分配呢?其实在MyVector中是给类分配了内存说白了就是给类中的成员变量分配了内存,而成员变量若有指针的话,它只是为指针分配了内存,而我们所需要的是分配指针所指向的内存空间分配内存)。
MyVector.h
#pragma once
#include<iostream>
using namespace std;
template <typename Type>
class MyVector
{
friend ostream& operator<< <Type> (ostream &out, const MyVector &obj);
//在泛型编程当中,类模板中避免使用友元函数,除了重载 "<<" ">>" 左移右移运输算符,其他的函数都写成成 //员函数
public:
MyVector(int len);
MyVector(const MyVector &obj);
~MyVector();
public:
MyVector& operator=(const MyVector &obj);
Type& operator[](int index);
private:
Type *mSpace;
int len;
};
MyVector.cpp
#include<iostream>
using namespace std;
#include"MyVector.h"
template <typename Type>
MyVector<Type>::MyVector(int len)
{
this->len = len;
mSpace = new Type[len];
}
template <typename Type>
MyVector<Type>::MyVector(const MyVector &obj)
{
this->len = obj.len;
mSpace = new Type[len];
for (int i = 0; i < len; i++)
{
mSpace[i] = obj.mSpace[i];
}
}
template <typename Type