C++ 使用指针访问std::字符串中的元素

C++ 使用指针访问std::字符串中的元素,c++,c++14,C++,C++14,如何使用指针访问std::string中的单个元素?是否可以不将类型强制转换为常量字符* #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; // ..

如何使用指针访问std::string中的单个元素?是否可以不将类型强制转换为常量字符*

#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;
}
#包括
#包括
使用名称空间std;
int main(){
//我正试着这么做。。。
string str=“这是一个字符串”;
cout有两种方法:

  • 显式调用
    运算符[]
    函数:

    std::cout << p_str->operator[](2) << '\n';
    
    这两者几乎是等价的

  • 或取消引用指针以获取对象,并使用普通索引:

    std::cout << (*p_str)[2] << '\n';
    

    所以你想通过指针访问字符串的第三个元素?这与通过指针访问任何其他类对象几乎相同。所有标准方法都适用。
    std::cout << (*p_str)[2] << '\n';