C++类模板

学了上节的知识,我们再来看看类模板

C++函数模板https://blog.csdn.net/qq_58665528/article/details/122424591

写一个可扩展的动态数组

//func.h

#pragma once
#include <iostream>

template<typename T>
class Array;						//一定要先写类声明

template<typename T>
std::ostream& operator<<(std::ostream& out, const Array<T>& array);	//写在类声明后面

template<typename T>
class Array {
private:
	T* m_address;	//数组首地址
	int m_size;		//数组现有元素个数
	int m_capacity;	//数组容量
	friend std::ostream& operator<< <>(std::ostream& out, const Array<T>& array);	//友元重载运算符函数
//如果<<是函数模板型重载就要写成<<<>
																													

public:
	Array(int capacity = 0);	//构造函数
	void add(T value);				//向数组增加一个元素
	T get(int index);					//返回当前下标的元素
	int size();								//返回数组现有元素个数
	T operator[](int index);	//重载运算符[]
	~Array();									//析构函数

};

template<typename T>
Array<T>::Array(int capacity) {
	this->m_size = 0;
	this->m_capacity = (capacity > 0) ? capacity : 10;
	this->m_address = new T[this->m_capacity];

}

template<typename T>
void Array<T>::add(T value) {
	if (this->m_size < this->m_capacity) {
		this->m_address[this->m_size++] = value;
	}
	else {
		this->m_capacity += this->m_capacity;
		T* address = new T[this->m_capacity];
		for (int i = 0; i < this->m_size; ++i) {
			address[i] = this->m_address[i];
		}
		delete[] this->m_address;
		this->m_address = address;
		this->m_address[this->m_size++] = value;

	}

}

template<typename T>
T Array<T>::get(int index) {
	if (index >= this->m_capacity || index < 0) {
		throw "数组下标越界";
	}

	return this->m_address[index];
}

template<typename T>
int Array<T>::size() {
	return this->m_size;
}

template<typename T>
T Array<T>::operator[](int index) {
	return this->get(index);
}

template<typename T>
Array<T>::~Array() {
	if (this->m_address != nullptr) {
		delete[] this->m_address;
		this->m_address = nullptr;
	}
}

template<typename T>
std::ostream& operator<<(std::ostream& out, const Array<T>& array) {
	out << "[";
	for (int i = 0; i < array.m_size; ++i) {
		if (i != 0) out << ", ";
		out << array.m_address[i];
	}
	out << "]";

	return out;
}
//main.cpp

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

int main(void) {
	Array<int> a;
	for (int i = 0; i < 11; ++i)
		a.add(i);

	std::cout << a;

	return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值