请设计一个数组模板类( Vector ),完成对 int 、 char 、 float 、 double 以 及任意的自定义类等类型元素进行管理。需求a. 实现构造函数b. 实现拷贝构造函数c. 实现 cout << 操作d. 实现下标访问符 [] 的重载操作e. 实现 = 号操作符重载
.h
#pragma once
#include <iostream>
using namespace std;
template<typename T>class Vector{
public:Vector();Vector(int len);//定义一个下标运算符重载T& operator[](int index);//获取数组长度int getLen();//设置拷贝构造函数,实现定义时赋值Vector(const Vector& other);//设置赋值运算符重载实现定义后赋值Vector& operator=(const Vector& other);~Vector();
private:int len;T* m_len;template<typename T>friend ostream& operator<<(ostream& os, Vector<T>& vector);
};
template<typename T>
ostream& operator<<(ostream& os, Vector<T>& vector) {for (int i = 0; i < vector.len; i++){os << vector.m_len[i] << endl;}return os;
}
.cpp
#include "Vector.h"
template<typename T>
Vector<T>::Vector()
{
}
template<typename T>
Vector<T>::Vector(int len){if (len>0){this->len = len;m_len = new T[len];}
}
//实现通过下标赋值
template<typename T>
T& Vector<T>::operator[](int index)
{return m_len[index];
}
//获取数组长度
template<typename T>
int Vector<T>::getLen()
{return len;
}
//拷贝构造函数
template<typename T>
Vector<T>::Vector(const Vector& other)
{//拷贝构造函数不存在判空this->len = other.len;m_len = new T[len];//开始数据拷贝for (int i = 0; i < other.len; i++){this->m_len[i] = other.m_len[i];}
}
//aa=bb=cc
template<typename T>
Vector<T>& Vector<T>::operator=(const Vector<T>& other){//需要进行判空,因为链式拷贝if (this->m_len!=NULL){delete[] m_len;m_len = NULL;len = 0;}//实现数据拷贝this->len = other.len;m_len = new T[len];//开始数据拷贝for (int i = 0; i < other.len; i++) {this->m_len[i] = other.m_len[i];}return *this;//实现链式拷贝,
}template<typename T>
Vector<T>::~Vector()
{if (m_len!=NULL){delete[] m_len;m_len = NULL;len = 0;}
}
主函数
#include <iostream>
#include <Windows.h>
#include "Vector.cpp"using namespace std;class Man {
public:Man() {age = 0;name ="位置";};Man(const char* name, int age) {this->name = name;this->age = age;}friend ostream& operator<<(ostream& os, Man& man);
private:int age;string name;
};
//函数重载Vector的左移运算符重载
ostream& operator<<(ostream& os, Man& man) {os << man.name <<" " << man.age << " ";return os;
}
int main(void) {Vector<int> aa(10);for (int i = 0; i < aa.getLen(); i++){aa[i] = i;}//调用拷贝构造函数Vector<int> aa1 = aa;//调用赋值构造函数Vector<int> aa2, aa3;aa3 = aa2 = aa;for (int i = 0; i < aa.getLen(); i++){cout << aa[i]<<" ";}system("pause");cout << "为浮点数时:" << endl;Vector<double> bb(4);for (int i = 0; i < bb.getLen(); i++) {bb[i] = i*0.1;}for (int i = 0; i < bb.getLen(); i++){cout << bb[i] << " ";}system("pause");//通过拷贝构造函数cout << "通过拷贝构造函数:" << endl;for (int i = 0; i < aa1.getLen(); i++){cout << aa1[i] << " ";}//通过赋值构造函数system("pause");cout << "通过赋值构造函数:" << endl;for (int i = 0; i < aa2.getLen(); i++){cout << aa2[i] << " ";}for (int i = 0; i < aa3.getLen(); i++){cout << aa3[i] << " ";}//调用外类实现数组存放Man man("李下滑", 23);Man man1("如花", 23);cout << man << endl;Vector<Man*> manM(2);manM[0] = &man;manM[1] = &man1;for (int i = 0; i < manM.getLen(); i++){cout<<*manM[i];}return 0;
}