简体   繁体   English

C++初始化后的数组赋值

[英]Array assignment after initialization in C++

I am reading TCPPPL by Stroustrup.我正在阅读 Stroustrup 的 TCPPPL。 In the topic "Array", I found this:在“数组”主题中,我发现了这一点:

char v4[3]={'a', 'b', 0};

Then it mentions that "there is no array assignment to match the initialization",ie the following gives an error:然后它提到“没有匹配初始化的数组分配”,即以下给出了错误:

void f()
{
v4={'c','d',0}; //error: no array assignment
}

What does the author mean here?作者在这里是什么意思? Does he mean that after initializing the array you can't re-assign it?他的意思是初始化数组后不能重新分配吗?

Does he mean that after initializing the array you can't re-assign it?他的意思是初始化数组后不能重新分配吗?

Yes.是的。 You cannot change "the array" that an array contains.您不能更改数组包含的“数组”。 You can change the values of each element in the array but you cannot assign an array to another array.您可以更改数组中每个元素的值,但不能将一个数组分配给另一个数组。

int a[] = {1,2,3};
int b[] = {4,5,6};
b = a; // this is also illegal

This is one reason to use standard containers like std::string , std::array , and std::vector .这是使用std::stringstd::arraystd::vector等标准容器的原因之一。 They are assignable and copyable (and moveable).它们是可分配和可复制的(和可移动的)。

What does the author mean here?作者在这里是什么意思? Does he mean that after initializing the array you can't re-assign it?他的意思是初始化数组后不能重新分配吗?

Yes, that's correct.对,那是正确的。 Although, you cannot assign an array before initializing it either, so that should be simplified to: "You cannot assign an array ".虽然,您也不能初始化之前分配数组,因此应将其简化为: “您不能分配数组”。

Just one interesting thing to note in addition to existing answers.除了现有答案之外,还有一件有趣的事情需要注意。 Clause 11.4.5 of C++ standard points out: C++标准第11.4.5条指出:

The implicitly-defined copy/move assignment operator for a non-union class X performs memberwise copy/move assignment of its subobjects... and if the subobject is an array, each element is assigned, in the manner appropriate to the element type."非联合类 X 的隐式定义复制/移动赋值运算符执行其子对象的成员复制/移动赋值......如果子对象是数组,则以适合元素类型的方式分配每个元素。 ”

So the following code is absolutely valid.所以下面的代码是绝对有效的。

struct { int c[3]; } s1, s2 = {3, 4, 5}; 
s1 = s2;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM