【发布时间】:2021-05-07 20:07:07
【问题描述】:
我想在构造函数中传递几个整数并像这样更改结构的字段:
struct testStruct
{
testStruct(int argIntArray[])
{
intArray = argIntArray;
}
int intArray[5];
};
void main()
{
testStruct test1(new int[5]{1,2,3,4,3});
}
但我不能那样做。 intArray = argIntArray; = "表达式必须是可修改的左值"。我可以像 intArray[0] = argIntArray[0]; 那样做,但这不是一个优雅的解决方案。
我知道我可以用指针表示法做到这一点,但有没有办法用数组表示法做到这一点?
【问题讨论】:
-
这是
std::array或std::vector优于数组的众多原因之一。 -
使用
std::copy()来做到这一点 -
@AlexanderZolkin 另外,您的解决方案一开始并不是很优雅,因为
new int[5]{1,2,3,4,3}是内存泄漏,因为您从不使用delete[]数组。也许std::initializer_list更适合你?testStruct(std::initializer_list<int> argInts) ... testStruct test1({1,2,3,4,3}); -
intArray = argIntArray;是错误的。复制条目。 -
A.只是不要在 C++ 中使用 C 数组,而是使用 std::array 或 std::vector ,并使用 std::span 来引用内存中任意连续的数据列表(gsl::span 可以在 C++ 之前使用20); B. C 数组是 C(然后是 C++)中的二等公民。像函数一样,它们可以被声明,但是一旦你使用它们,它们就会衰减为指向它们的第一个元素的指针(即 &a[0])。它们不能按值传递或引用,并且它们具有超级不稳定的语义(C++ 允许像
T (&)[N]这样的东西根本没有帮助)。远离他们,你的生活会更轻松。