【[C++] 通用类型数组】幽沉谢世事,俯默窥唐虞。这篇文章主要讲述[C++] 通用类型数组相关的知识,希望能为你提供帮助。
主函数
#include "通用类型数组.hpp"
class Person
public:
Person() ;
Person(string name, int age)
this-> m_name = name;
this-> m_age = age;
string m_name;
int m_age;
;
void myprintint(MyArray< int> & myintarray)
for (int i = 0; i < myintarray.getsize(); i++)
cout < < myintarray[i] < < endl;
void myprintperson(MyArray< Person> & mypersonarr)
for (int i = 0; i < mypersonarr.getsize(); i++)
cout < < "姓名 = " < < mypersonarr[i].m_name < < " 年龄 =" < < mypersonarr[i].m_age < < endl;
int main()
//int
MyArray< int> myintarray(100);
for (int i = 0; i < 10; i++)
myintarray.pushback(i + 100);
myprintint(myintarray);
cout < < "-----" < < endl;
//Person
MyArray< Person> mypersonarr(100);
Person p1("孙悟空", 1);
Person p2("猪八戒", 2);
Person p3("沙悟净", 3);
Person p4("唐三藏", 4);
mypersonarr.pushback(p1);
mypersonarr.pushback(p2);
mypersonarr.pushback(p3);
mypersonarr.pushback(p4);
myprintperson(mypersonarr);
cout < < "容量大小 = " < < mypersonarr.getcapacity() < < endl;
cout < < "数组大小 = " < < mypersonarr.getsize() < < endl;
return 0;
头文件
#pragma once
#include < iostream>
#include < string>
using namespace std;
//类模板
template< class T>
class MyArray
public:
//除非用户提供默认capacity 否则数组必须有默认构造
//有参构造
MyArray(int capacity)
this-> m_capacity = capacity;
this-> m_size = 0;
this-> paddress = new T[this-> m_capacity];
//拷贝构造
MyArray(const MyArray& arr)
this-> m_capacity = arr.capacity;
this-> m_size = arr.m_size;
this-> paddress = new T[this-> m_capacity];
for (int i = 0; i < arr.m_size; i++)
this-> paddress[i] = arr.paddress[i];
//重载=
MyArray& operator = (const MyArray& arr)
if (this-> paddress)
delete[] this-> paddress;
this-> paddress = NULL;
this-> m_capacity = arr.capacity;
this-> m_size = arr.m_size;
this-> paddress = new T[this-> m_capacity];
for (int i = 0; i < arr.m_size; i++)
this-> paddress[i] = arr.paddress[i];
return *this;
//重载[]
T& operator[](int index)
return this-> paddress[index];
//尾插法
void pushback(const T& val)
if (this-> m_capacity < = this-> m_size)
return;
this-> paddress[this-> m_size]推荐阅读
- 3.FastAPI参数
- 教程手把手教你如何搭建Hadoop单机伪集群
- Java&Go高性能队列之LinkedBlockingQueue性能测试#yyds干货盘点#
- OpenHarmony 源码解析之账号子系统
- 云系统中的异常检测方法
- Spring专场「MVC容器」不看源码就带你认识核心流程以及运作原理
- 1月活动|51CTO博客#IT话题共建#,挑战7日连更!
- MyBatis 快速入门
- Go 每日一库之 gorilla/securecookie