使用指针访问std :: string中的元素

sam*_*sam 2 c++ c++14

如何使用指针访问std :: string中的各个元素?没有类型转换为const char *是否可能?

#include <iostream>
#include <string>
using namespace std;

int main() {

    // I'm trying to do this...
    string str = "This is a string";
    cout << str[2] << endl;

    // ...but by doing this instead
    string *p_str = &str;
    cout << /* access 3rd element of str with p_str */ << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 7

有两种方法:

  1. operator[]显式调用该函数:

    std::cout << p_str->operator[](2) << '\n';
    
    Run Code Online (Sandbox Code Playgroud)

    或使用at功能

    std::cout << p_str->at(2) << '\n';
    
    Run Code Online (Sandbox Code Playgroud)

    两者几乎相等。

  2. 或者取消引用指针以获取对象,并使用常规索引:

    std::cout << (*p_str)[2] << '\n';
    
    Run Code Online (Sandbox Code Playgroud)

无论哪种方式,都需要取消引用指针。通过“箭头”运算符->或与直接取消引用运算符*无关紧要。