这是有效的 C++ 代码吗?这不起作用

Is this valid C++ code? This doesn't work how it supposed to be

int main() {
    
    string str[5] = "ABCD";
    std::cout << str[3] << std::endl;
    std::cout << str[0] << std::endl;
    return 0;
}

此代码打印:

ABCD

ABCD

没看懂,str[3]怎么打印出ABCD

编译器:GCC 6.3

您可以试试这个来编译您的代码:

string str[5] = {"ABCD", "", "", "", ""};

str[3] 在你的代码中意味着 4the 数组的字符串,如果你编译它的话。

但您很可能想要:

char str[5] = "ABCD";

字符串和字符不是一回事。如果您想访问字符串中的单个字符,则不需要字符串数组。您只需要一个字符串:

string str = "ABCD";

std::cout << str[3] << std::endl;

该代码不是有效的 C++ 代码,不应编译。它不适用于高于 7 的 clang 和 gcc 版本。这很可能是旧版本 gcc 中的错误,已在版本 7 中修复。

std::string str[5]

您这里有一个包含 std::string 的 5 个元素的 C 数组。这就是您初始化它的方式:

std::string strings[5] = {"1st string", "2nd string", "3rd string", "4th string", "5th string"};

在这种情况下,strings[0] 将是 "1st string",而 strings[3] 将是 "4th string"

但是不要这样做。不要在 C++ 中使用 C 数组。如果需要字符串数组,请使用 std::vectorstd::arraystd::array<std::string> stringsstd::vector<std::string> strings

话虽这么说,但我怀疑您只需要一个字符串,又名:

std::string str = "ABCD";

在这种情况下 str[0]'A'str[3]'D'

如果我没有错,因为我不喜欢 C++ 语言,那么发生的事情是:

string str[5] = "ABCD"; 只是 copying/initializing 变量 str 的所有索引,其值为 ABCD,如 str[0] = "ABCD", str[1] = "ABCD",依此类推。

因此,当您 运行 std::cout << str[3] << std::endl;std::cout << str[0] << std::endl; 时,您将从字符串变量的相应索引中获取值。

希望我没看错。 :(