[C++] 通用类型数组

Posted 咸菜萝卜干

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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] Android 逆向Android 逆向通用工具开发 ( Android 平台运行的 cmd 程序类型 | Android 平台运行的 cmd 程序编译选项 | 编译 cmd 可执行程序 )(代码片段

C++在类中定义vector并初始大小的问题

为啥此代码片段返回意外结果?

对数组中的字符串进行排序,使其稀疏

如何使用方法写入通用数组?指定类型后,通用数组不会更改数据类型

C++ Primer Plus学习:第四章