简体   繁体   English

如何在C ++中创建字符串类型?

[英]How is the string type created in c++?

How was the "string" type created in C++? 如何在C ++中创建“字符串”类型? In C, strings are character arrays, but how did C++ turn the character arrays into the "strings" we know of in C++? 在C中,字符串是字符数组,但是C ++如何将字符数组转换为我们在C ++中认识的“字符串”?

The character array is still in there, it just has a class wrapped around it. 字符数组仍在其中,只是包装了一个类。 Imagine something like this: 想象这样的事情:

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;
  }
};

That's obviously a very incomplete example, but you get the idea, right? 显然这是一个非常不完整的示例,但是您知道了,对不对?

The actual implementation of std::string is pretty comprehensive, but it's nothing you couldn't do yourself. std :: string的实际实现是非常全面的,但是您无法做任何事。 Here's some differences in the official std::string class from what I posted: 这与我发布的官方std :: string类有所不同:

  • The length of the string is usually included as a member variable, so you don't have to keep calling strlen to find the length. 字符串的长度通常作为成员变量包含在内,因此您不必继续调用strlen来查找长度。
  • The std::string class uses templates, so you're not limited to the char type. std :: string类使用模板,因此您不仅限于char类型。 If you're using Unicode, you can use std::wstring, which uses 16- or 32- bit strings by replacing the char type with the wchar_t type. 如果使用的是Unicode,则可以使用std :: wstring,它通过将char类型替换为wchar_t类型来使用16位或32位字符串。
  • Usually there's lots of optimizations to choose from. 通常,有很多优化可供选择。 Lately the most popular has been the "short string" optimization. 最近最流行的是“短字符串”优化。

Once you've relatively comfortable with C++, you should try writing your own string class. 一旦相对熟悉C ++,就应该尝试编写自己的字符串类。 It's not something you would use in practice, but it's a really good exercise for library writing. 这不是您在实践中将要使用的东西,但是对于库编写而言,这确实是一个很好的练习。

By writing a class that encapsulated a lot of string functions, and by overloading a bunch of operators. 通过编写一个封装了许多字符串函数的类,并通过重载一堆运算符。

string really is just a class like any other: 字符串真的只是一个像其他类一样的类:

 string s = "hello"

is an overload of the equals operator defined: 是定义的equals运算符的重载:

 string& operator= ( const char* s );

for example. 例如。

It's just a class named 'string', something like this: 这只是一个名为“字符串”的类,如下所示:

class string
{
private:
    //members
    char* c;
public:
    //methods
    bool operator==(const string& other) const;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM