這篇文章主要介紹了如何使用c++模板自定義數組,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
前言:
制造通用模板,創建自定義的數組,
一個數組,里面有這么幾個屬性,數組容量,數組元素個數,數組本身內存地址,這幾個數據都是定義私有類型,提供有參構造,讓用戶可以構造出這個數組對象。下面是有參構造和拷貝構造和析構函數還有operator=重載的代碼
在前面類模板中成員函數創建有這個主意問題,最好的辦法就是把類模板寫在一個hpp的文件中,不要拆開寫成多個文件
#pragma once
#include<iostream>
using namespace std;
#include<string>
template<class T>
class Myarry
{
public:
Myarry() {};//自己創建有參構造,編譯器就不提供無參構造,所以必須自己寫一次無參構造,即使是空實現也要寫!
Myarry(int capacity)//有參構造函數
{
this->capacity = capacity;
this->size = 0;
this->marry = new T[this->capacity];//把數組創建在堆區
}
~Myarry()//析構函數
{
if (this->marry !=NULL)
{
delete []this->marry;//析構數組必須加[],否則會引發斷點
marry = NULL;
this->capacity = 0;
this->size = 0;
}
}
Myarry(const Myarry& arr)//拷貝構造
{
this->capacity = arr.capacity;
this->size = arr.size;
this->marry = new T[arr.capacity];
for (int i = 0; i < arr.size; i++)//把數據拷貝過來
{
this->marry[i] = arr->marry[i];
}
}
//等號賦值
Myarry& operator=(const Myarry& arr)
{
if (this->marry != NULL)//如果有數據先清空,再賦值
{
delete[]this->marry;
this->marry = NULL;
this->size = 0;
this->capacity = 0;
}
this->capacity = arr.capacity;
this->size = arr.size;
this->marry = new T[this->capacity];
for (int i = 0; i < this->size; i++)//將數據進行拷貝
{
this->marry[i] = arr.marry[i];
}
return *this;
}
void pushback(const T&ptr)//尾加法
{
if (this->capacity == this->size)
{
cout << "容量已滿!" << endl;
return;
}
this->marry[this->size] = ptr;
this->size++;
}
void deleteback()//尾刪法
{
if (this->size == 0)
{
cout << "數據為零,沒有可刪數據!" << endl;
}
delete this->marry[this->size - 1];
this->size--;
}
T & operator[](int index)//通過下標訪問數組,并使它作為左值加&
{
if (index > this->capacity)
{
cout << "訪問越界!" << endl;
exit(0);
}
return this->marry[index];
}
int gercapacity()//獲取數組容量
{
return this->capacity;
}
int getsize()//獲取數組元素個數
{
return this->size;
}
private:
T * marry;//數組
int capacity;//數組容量
int size;//數組元素個數
};#include "自定義數組.hpp"
class person
{
public:
person()
{
this->age = 0;
}
int age;
string name;
};
void text01()
{
person p[4];
p[0].age = 20;
p[0].name = "張三";
p[1].age = 0;
p[1].name = "李四";
p[2].age = 40;
p[2].name = "王五";
p[3].age = 80;
p[3].name = "趙六";
Myarry<person>pp(10);
for (int i = 0; i < 4; i++)
{
pp.pushback(p[i]);
}
for (int i = 0; i < pp.getsize(); i++)
{
cout << pp[i].name<<pp[i].age<< endl;
}
}
void text02()
{
Myarry<int>inta(10);
for (int i = 0; i < 5; i++)
{
inta.pushback(i);
}
for (int i = 0; i < inta.getsize(); i++)
{
cout << inta[i] << endl;
}
}
int main()
{
/*text02();*/
text01();
return 0;
}感謝你能夠認真閱讀完這篇文章,希望小編分享的“如何使用c++模板自定義數組”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。