第九天之类模板在项目开发中的应用案例_数组模板类

类模板小结
模板是 C++类型参数化的多态工具。C++提供函数模板和类模板。
模板定义以模板说明开始。类属参数必须在模板定义中至少出现一次。
同一个类属参数可以用于多个模板。
类属参数可用于函数的参数类型、返回类型和声明函数中的变量。
模板由编译器根据实际数据类型实例化,生成可执行代码。实例化的函数。
模板称为模板函数;实例化的类模板称为模板类。
函数模板可以用多种方式重载。
类模板可以在类层次中使用 。

训练题
1) 请设计一个数组模板类( MyVector ),完成对int、char、Teacher类型元素的管理。

MyVector.h

#pragma once

#include <iostream>
using namespace std;

template <typename T>
class MyVector
{
public:
	friend ostream& operator<< <T>(ostream& out, const MyVector& obj);

	MyVector(int size = 0);			//构造函数
	MyVector(const MyVector &obj);	//拷贝构造函数
	~MyVector();					//析构函数
	int GetLen()
	{
		return m_len;
	}

public:
	T& operator[](int index);
	MyVector& operator=(const MyVector& obj);
	
private:
	T	*m_space;
	int m_len;

};


MyVector.cpp

#include "MyVector.h"
#include <iostream>

using namespace std;

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

template <typename T>
MyVector<T>::MyVector(int size = 0)			//构造函数
{
	m_space = new T[size];
	m_len = size;
}
//MyVector<int> myvl2 = myvl;
template <typename T>
MyVector<T>::MyVector(const MyVector &obj)	//拷贝构造函数
{
	m_len = obj.m_len;
	m_space = new T[m_len];

	for (int i = 0; i < m_len; i++)
	{
		m_space[i] = obj.m_space[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];
}

//a1 = a2
template <typename T>
MyVector<T>& MyVector<T>::operator=(const MyVector& obj)
{
	//先把旧内存a1释放掉
	if (m_space != NULL)
	{
		delete[] m_space;
		m_space = NULL;
		m_len = 0;
	}
	m_len = obj.m_len;
	//再根据a2分配新内存
	m_space = new T[m_len];

	return *this;
}

MyVector_test.cpp

#include "MyVector.cpp"
#include <iostream>

using namespace std;


void main()
{
	MyVector<int> myvl(10);
	for (int i = 0; i < myvl.GetLen(); i++)
	{
		myvl[i] = i + 1;
		cout << myvl[i] << " ";
	}
	cout << endl;

	MyVector<int> myvl2 = myvl;
	for (int i = 0; i < myvl2.GetLen(); i++)
	{
		cout << myvl2[i] << " ";
	}
	cout << endl;
	cout << myvl2 << endl;
	system("pause");
}

结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值