字符串库如何在C++中工作?

ipk*_*iss 1 c++ string

根据http://www.cplusplus.com/reference/string/string/上的文字,C++中的字符串库是一个类,而不仅仅是"内存数组中的单纯字符序列".我写了这段代码以了解更多信息:

string s = "abcd";

cout << &s << endl; // This gives an address
cout << s[0] << endl; // This gives 'a'
cout << &s[0] << endl; // This gives "abcd"
Run Code Online (Sandbox Code Playgroud)

我有一些问题:1.C++中的字符串库是否仍然是一个序列字符数组?2.如何获取字符串中每个字符的地址?(在代码中,我可以检索每个字符,但无法获取其地址& operator)

Jer*_*fin 5

很多(大多数)这不是关于字符串类本身.

std::string 将其内容存储为连续的字符数组.

&s[0]将产生该数组的开头的地址 - 但是 std::ostream具有operator<<指向char的指针的重载,并将其作为字符串打印.

如果要查看字符串中单个字符的地址,则需要获取其地址,然后将每个地址转换为指向void的地址.std::iostream还有一个重载,operator<<它接受一个指向void的指针,并且该重载打印出地址而不是(它假设)在该地址的字符串.

编辑:演示代码:

#include <iostream>
#include <string>

int main(){
    std::string x("this is a string");

    std::cout << &x[0] << "\n";
    std::cout << (void *)&x[0] << '\n';
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

结果:

this is a string
00481DE0
Run Code Online (Sandbox Code Playgroud)