過載技巧 簡單實現string和Vector

2021-06-25 09:20:12 字數 2430 閱讀 8870

1. 賦值(=),下標(),呼叫(())和成員訪問箭頭(->)等操作符必須定義為成員,將這些操作符定義為非成員函式將在編譯時標記為錯誤。

2. 像賦值一樣,復合賦值操作符通常應定義為類的成員。與賦值不同的是,不一定非得這樣做,如果定義為非成員復合賦值操作符,不會出現編譯錯誤。

3. 改變物件狀態或與給定型別緊密聯絡的其他一些操作符,如自增,自減和解引用,通常應定義為類成員。

4. 對稱的操作符,如算術操作符,相等操作符,關係操作符和位操作符,最好定義為普通非成員函式。

5.io操作符必須定義為非成員函式,過載為類的友元。

#include#includeusing namespace std;

class string

iterator begin()

iterator end()

string substr(string::iterator pstart,size_type len);

//operator

bool operator==(const string& other);

string& operator+=(const string&);

friend ostream& operator<<(ostream& os, const string& str);

private:

size_t strlength;

char *pstr;

};string::string(const char *str)

void push_back(const t&);

void reserve(const size_t capa);

//調整vector大小,使其能容納n個元素;

//如果n小於vector當前大小,則刪除多餘元素

//否則,新增採用值初始化的新元素

void resize(const size_t n);

//調整vector大小,使其能容納n個元素,新增所有元素的值都為t

void resize(const size_t n ,const t& t);

//下標操作

const t& operator(const size_t) const;

t& operator(const size_t );

//返回vector大小

size_t size()

//返回容量

size_t capacity()

private:

static std::allocatoralloc;//用於獲取未構造記憶體的物件

void reallocate();//獲得更多空間並複製現有元素

t* elements;//指向第乙個元素的指標

t* first_free;//指向第乙個自由元素的指標

t* end; //指向陣列末端的下乙個元素位置的指標

}#endif

//cpp vector實現

//templateallocatorvector::alloc;

templatevoid vector::push_back(const t& t)

templatevoid vector::reallocate()

//釋放舊元素占用的記憶體

if (elements)

//使資料結構指向新元素

elements=newelements;

first_free=elements+size;

end=elements+newcapacity;

}templatevoid vector::reserve(const size_t capa)else

//逆序撤銷記憶體中構造的物件

for(t*p=first_free;p!=elements; )

//釋放舊元素占用的記憶體

if (elements)

//使資料結構指向新元素

elements=newelements;

first_free=elements+min(size,capa);

end=elements+capa;

}templatevoid vector::resize(const size_t n)else if(n>size)else

//使資料結構指向新元素

first_free=elements+n }

templatevoid vector::resize(const size_t n,const t &t)else if(n>size)else

//使資料結構指向新元素

first_free=elements+n }

templatet& vector::operator(const size_t index)

templateconst t& vector::operator(const size_t index) const

c 簡單實現 string

學習了c 其中stl是當之無愧的佼佼者。簡單實現一些stl容器 string,只寫了部分功能。模擬實現乙個簡單的stirng容器 pragma once define crt secure no warnings 1 include include include using namespace s...

string類的簡單實現

include class string string string const char ch else string string const string str string string string string operator const string str string stri...

string類的簡單實現

string類是stl裡面個乙個基礎類,同時也是乙個容器。stl在string類裡面塞了很多東西,大概有106個成員函式,以及大量的typedef 巨集,晦澀難懂。本文只是簡單通過物件導向的方法簡單實現了乙個string,以後會在此基礎進行擴充和改進。ifndef mystring h define...