泛型编程

//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;


}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值