欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

类模板和Vector

程序员文章站 2022-06-01 11:52:17
...

**

关于类模板与Vector容器

**

Vector.h

#pragma once
template <typename T>
class Vector
{
public:
	Vector();
	Vector(int length);
	Vector(const Vector& object);
	~Vector();
	T& operator[](int length);	//in[0] = 1;
	Vector& operator=(const Vector& object);//in[0] = 1;
private:
	T* base;
	int length;
};

Vector.cpp

#include "Vector.h"

template <typename T>
Vector<T>::Vector()	//默认构造函数
{
	base = new T[1];
	strcpy_s(base, 1, "");	//T* base;  base = "";
	length = 0;
}

template <typename T>
Vector<T>::Vector(int length)	//自定义构造函数
{
	if (length > 0)
	{
		this->length = length;
		this->base = new T[length];
	}
}

template <typename T>
Vector<T>::Vector(const Vector<T>& object)	//拷贝构造函数
{
	length = object.length;
	base = new T[length];

	for (int i = 0; i < length; i++)
	{
		base[i] = object.base[i];
	}
}

template<typename T>
Vector<T>::~Vector()	//析构函数
{
	if (base)
	{
		delete[] base;
		base = 0;
		length = 0;
	}
}

template <typename T>
T &Vector<T>::operator[](int length)	//下标运算符重载
{
	return base[length];
}

template <typename T>
Vector<T>& Vector<T>::operator=(const Vector<T>& object)	//赋值运算符重载
{
	if (base)
	{
		delete[] base;
		base = 0;
		length = 0;
	}

	length = object.length;
	base = new T[length];

	for (int i = 0; i < length; i++)
	{
		base[i] = object.base[i];
	}

	return *this;	//返回对象本身
}

main.cpp

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

class Demo
{
	friend std::ostream& operator<<(std::ostream& os, Demo& demo);	//声明友元输出运算符重载

public:
	Demo() {	//默认构造函数
		name = new char[3];
		strcpy_s(name, 3, "空");
		age = 0;
	}
	Demo(const char*name, int age)	//自定义构造函数
	{
		this->name = new char[strlen(name)+1];
		strcpy_s(this->name, strlen(name) + 1, name);
		this->age = age;
	}
	Demo(const Demo& demo) {	//拷贝构造函数
		name = new char[strlen(demo.name)+1];	// +1 文件结束符
		strcpy_s(name, strlen(demo.name) + 1, demo.name);
		age = demo.age;
	}

	Demo& operator = (const Demo& demo) {	//赋值运算符重载
		if (name) {
			delete[] name;
			name = NULL;
		}
		name = new char[strlen(demo.name) + 1];
		strcpy_s(name, strlen(demo.name) + 1, demo.name);
		age = demo.age;

		return *this;
	}

	

private:
	char* name;
	int age;
};

std::ostream& operator<<(std::ostream& os, Demo& demo)	//输出运算符重载 std::cout << demo[0] << std::endl;
{
	os << "name: " << demo.name << ", age: " << demo.age;
	return os;
}

int main()
{
	Demo demo1("XYL", 21);
	Demo demo2("Martin", 30);
	Vector<Demo> demo(3); //存放了3个Demo类的对象

	demo[0] = demo1;
	demo[1] = demo2;
	
	std::cout << demo[0] << std::endl;
	std::cout << demo[1] << std::endl;
	std::cout << demo[2] << std::endl;


	return 0;
}

输出如下

类模板和Vector

相关标签: 类模板 c++