[英]size and the type of object created by the vector string constuctor in C++
[英]How is the string type created in c++?
如何在C ++中創建“字符串”類型? 在C中,字符串是字符數組,但是C ++如何將字符數組轉換為我們在C ++中認識的“字符串”?
字符數組仍在其中,只是包裝了一個類。 想象這樣的事情:
class String
{
private:
char* stringData;
public:
String(const char* str)
{
stringData = new char[strlen(str)+1];
strcpy(stringData, str);
}
~String() { delete[] stringData; }
String& operator += (const String& rhs)
{
char* newStringData = new char[strlen(rhs) + strlen(stringData) + 1];
strcpy(newStringData, stringData);
strcpy(newStringData + strlen(stringData), rhs);
delete[] stringData;
stringData = newStringData;
return *this;
}
};
顯然這是一個非常不完整的示例,但是您知道了,對不對?
std :: string的實際實現是非常全面的,但是您無法做任何事。 這與我發布的官方std :: string類有所不同:
一旦相對熟悉C ++,就應該嘗試編寫自己的字符串類。 這不是您在實踐中將要使用的東西,但是對於庫編寫而言,這確實是一個很好的練習。
通過編寫一個封裝了許多字符串函數的類,並通過重載一堆運算符。
字符串真的只是一個像其他類一樣的類:
string s = "hello"
是定義的equals運算符的重載:
string& operator= ( const char* s );
例如。
這只是一個名為“字符串”的類,如下所示:
class string
{
private:
//members
char* c;
public:
//methods
bool operator==(const string& other) const;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.