這篇文章給大家介紹C++ 中怎么實(shí)現(xiàn)數(shù)組類泛型編程,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
創(chuàng)新互聯(lián)建站專業(yè)為企業(yè)提供興文網(wǎng)站建設(shè)、興文做網(wǎng)站、興文網(wǎng)站設(shè)計(jì)、興文網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)與制作、興文企業(yè)網(wǎng)站模板建站服務(wù),十載興文做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。
原創(chuàng):
C++ 簡單實(shí)現(xiàn)數(shù)組類泛型編程示例
1、使用模板來實(shí)現(xiàn)泛型編程
2、本數(shù)組應(yīng)該能夠存儲(chǔ)各種基礎(chǔ)類型,各種復(fù)雜的類類型
3、應(yīng)該實(shí)現(xiàn)部分操作符重載
其實(shí)操作符重載滿滿的都是套路。
代碼如下:
點(diǎn)擊(此處)折疊或打開
模板類實(shí)現(xiàn):
#include#include #include using namespace std; template class myarray { private: T* array; unsigned int lenth; public: myarray(); myarray(unsigned int len); myarray(const myarray& a); myarray& operator=(const myarray& b); T& operator[](int ind); ~myarray(); }; template myarray ::~myarray() { if(this->array != NULL) { delete [] this->array; this->array = NULL; } } template myarray ::myarray() { this->array = NULL; this->lenth = 0; } template myarray ::myarray(unsigned int len) { this->array = new T[len]; this->lenth = len; memset(this->array,0,sizeof(T)*len); } template myarray ::myarray(const myarray & a) { int i; this->lenth = a.lenth; this->array = new T[a.lenth]; memset(this->array,0,sizeof(T)*a.lenth); for(i=0;i array+i) = *(a.array+i); } } template myarray & myarray ::operator=(const myarray & a) { if(this->array != NULL) { delete [] this->array;//調(diào)用類的析構(gòu)函數(shù)不能用free this->array = NULL; } this->array = new T[a.lenth]; this->lenth = a.lenth; for(int i=0;i array+i) = *(a.array+i);//元素對(duì)象復(fù)制調(diào)用對(duì)象的=操作符重載 } return *this; } template T& myarray ::operator[](int ind) { if(ind>=this->lenth) { exit(10); } return *(this->array+ind); } #include #include #include #include"arra.cpp" using namespace std; class test { private: int a; int b; char* myc; public: test() { a = 0; b = 0; myc = NULL; } test(const test& a) { this->a = a.a; this->b = a.b; this->myc = (char*)calloc(strlen(a.myc)+1,0); strcpy(this->myc,a.myc); } friend ostream& operator<<(ostream& out,test& a) { out< myc != NULL) { free(this->myc); this->myc = NULL; } this->a = a.a; this->b = a.b; this->myc = (char*)calloc(strlen(a.myc)+1,0); strcpy(this->myc,a.myc); return *this; } test& operator=(const char* a) { if(this->myc != NULL) { free(this->myc); this->myc = NULL; } if(a == NULL) { this->myc = (char*)calloc(1,0); return *this; } this->myc = (char*)calloc(strlen(a)+1,0); strcpy(this->myc,a); return *this; } }; int main() { myarray a(3); //測試class類數(shù)組 a[0] = "asdasd"; a[1] = "test"; a[2] = "kkkk"; myarray b(3); //測試int數(shù)組 b[0] = 1; b[1] = 2; b[2] = 3; myarray c(3); //測試char數(shù)組 c[0] = 'a'; c[1] = 'b'; c[2] = 'c'; myarray d = a;//測試myarray拷貝構(gòu)造函數(shù) for(int i=0;i<3;i++) { cout<
關(guān)于C++ 中怎么實(shí)現(xiàn)數(shù)組類泛型編程就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。