模板类实现vector容器
1.Vector.h
#pragma once
#include <iostream>
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
template <typename T>
class Vector {
public:
Vector(); //默认构造函数
Vector(int size = 64); //带参数的构造函数
Vector(const Vector& other); //拷贝构造函数
~Vector(); //析构函数
int GetLength() const; //返回容器元素个数
T* GetBase() const; //返回元素储存地址
T& operator[](int sub); //重载[]号运算符
Vector& operator=(const Vector& other); //重载=号运算符
friend ostream& operator<< <T> (ostream& os, const Vector& nums); //使用外部函数作为友元函数实现<<号的重载,特别注意因为使用了模板类而加上的<T>
private:
int length = 0; //容器大小
T* base = nullptr; //储存首地址
};
2.Vector.cpp
#include "Vector.h"
using namespace std;
template <typename T>
Vector<T>::Vector()
{
}
template<typename T>
Vector<T>::Vector(int size) //带参数的构造函数
{
if (size > 0) {
length = size;
base = new T[size];
}
else {
cout << "参数错误" << endl;
}
}
template<typename T>
Vector<T>::Vector(const Vector<T>& other) //拷贝构造函数
{
this->base = new T[other.length];
this->length = other.length;
memcpy_s(this->base, sizeof(T) * this->length, other.base, sizeof(T) * this->length);
}
template<typename T>
Vector<T>::~Vector() //析构函数
{
if (base) {
delete []base;
base = nullptr;
length = 0;
}
}
template<typename T>
int Vector<T>::GetLength() const //取得容器的大小
{
return length;
}
template<typename T>
T* Vector<T>::GetBase() const
{
return base;
}
template<typename T>
T& Vector<T>::operator[](int sub)
{
if (sub >= 0) {
return base[sub];
}
else {
cout << "参数越界" << endl;
}
}
template<typename T>
Vector<T>& Vector<T>::operator=(const Vector<T>& other)
{
if (this->base) {
delete[]base;
base = nullptr;
base = new T[other.length];
this->length = other.length;
memcpy_s(this->base, sizeof(T) * other.length, other.base, sizeof(T) * other.length);
}
return *this;
}
template<typename T>
ostream& operator<< (ostream& os,const Vector<T>& nums)
{
for (int count = 0; count < nums.length; ++count) {
os << nums.base[count] << " ";
}
cout << endl;
return os;
}
3.main.cpp
#include <iostream>
#include "Vector.cpp"
using namespace std;
int main(void) {
Vector<int> nums(5);
for (int count = 0; count < nums.GetLength(); ++count) {
nums[count] = count * 5;
}
cout << nums; //使用重载的<<号输出nums里的所有元素
Vector<int> nums1(nums); //调用拷贝构造函数
cout << nums1; //使用重载的<<号输出nums1里的所有元素
Vector<int> nums2(10);
nums2 = nums1; //调用赋值构造函数
cout << nums2; //使用重载的<<号输出nums2里的所有元素
system("pause");
return 0;
}
使用了类文件分离的写法。即类的声明写在头文件里,定义写在.cpp里,main函数写在另一个.cpp文件里。工程项目一般是这样操作的,所以要习惯这种写法。
另一个特别重要的点是,友元函数里有模板类时需要加上一个< T >,要不然是过不了编译的。具体加在那,可以看我上面写的代码。