gpt4 book ai didi

c++ - 声明类型之前/之后的数组赋值

转载 作者:搜寻专家 更新时间:2023-10-31 02:07:53 27 4
gpt4 key购买 nike

在我声明类型的同一行赋值,在以下示例中没有返回错误并正确编译:

#include <iostream>
int main() {
char c[5] = "Hey!";
}

但以下代码无法编译,因为我们知道,数组赋值在 c++ 中是不可能的。

#include <iostream>
int main() {
char c[5];
c = "Hey!"; //ERROR: expression must be a modifiable lvalue.
}

最佳答案

初始化和赋值是有区别的。在第二个示例中,您要做的不是初始化,而是赋值。但是在 C++ 中,这种对数组的赋值是不可能的。

声明数组时,只能对数组进行多次赋值:

char c[5] = "Hey!"; 

相当于

char c[5] = {'H', 'e', 'y', '!', '\0'};

声明后,您必须单独分配每个值,即

c[0] = 'H';
c[1] = 'e';
c[2] = 'y';
c[3] = '!';
c[4] = '\0';

或者,您可以使用 STL 容器,在这种情况下(字符数组)std::string 是合适的:

std::string c;
c = "Hey!;

关于c++ - 声明类型之前/之后的数组赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48239917/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com