为什么字符串可以这样使用

Why strings can be used like this

C++代码

string *stra;
string strb = "ABC";
stra = &strb;
std::cout <<  stra[0][1] << std::endl;
std::cout << *stra << " " << stra[0]<< std::endl;

为什么使用 stra[0]*stra 上打印相同或者为什么我可以那样使用

根据定义(正如@MikeCAT 所说)操作 A[B](对于普通数组)定义为 *(A + B)

这是数组索引操作——获取数组元素的值。在 C/C++ 中,普通数组通常仅由指针表示。此操作允许在第 B 个索引处读取数组 A 的值。

只是取消引用运算符 *A 等同于说 *(A + 0)。因此 A[0]*A.

的作用相同

根据 C++ 14 标准(5.2.1 下标)

1 A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall have the type “array of T” or “pointer to T” and the other shall have unscoped enumeration or integral type. The result is of type “T.” The type “T” shall be a completely-defined object type.64 The expression E1[E2] is identical (by definition) to *((E1)+(E2)) [ Note: see 5.3 and 5.7 for details of * and + and 8.3.4 for details of arrays. — end note ], except that in the case of an array operand, the result is an lvalue if that operand is an lvalue and an xvalue otherwise.

所以表达式 stra[0] 的计算方式与 *( stra + 0 ) 相同,与 *stra.

相同

注意,由于操作 + 是可交换的,因此此表达式 *( stra + 0 )*( 0 + stra ) 相同。这意味着您甚至可以写 0[stra] 而不是 stra[0].

这是一个演示程序,它使用字符串 litarals 而不是 std::string 类型的对象。

#include <iostream>

int main() 
{
    std::cout << "Heelo"[0] << ' ' << *"Hello" << '\n';
    
    return 0;
}

程序输出为

H H

C++ 中的字符串文字由常量字符数组表示。例如,字符串文字 "Hello" 的存储方式类似于未命名的字符数组

const char unnamed_string_literal[] = { 'H', 'e', 'l', 'l', 'o', '[=12=]' };

在带有取消引用运算符 * 或下标运算符 [] 的表达式中使用时,它们将转换为指向其类型 const char * 的第一个元素的指针。因此这个声明

    std::cout << "Heelo"[0] << ' ' << *"Hello" << '\n';

输出字符串文字的第一个字符"Hello"