繁体   English   中英

更改整个右值数组

[英]Change whole rvalue array

我想在构造函数中传递几个整数并更改结构的字段,如下所示:

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]; ,但这不是一个优雅的解决方案。

我知道我可以用指针表示法来做到这一点,但是有没有办法用数组表示法来做到这一点?

考虑到我的局限性(我只能使用 C 函数), memmove()可以解决问题:

#include <cstring>

const unsigned int markArraySize = 5;

struct TestStruct
{
  TestStruct(int argIntArray[])
  {
    memmove(intArray, argIntArray, sizeof(int)*markArraySize);
  }

  int intArray[markArraySize];
};

int main()
{
  int testArray[5] = {1, 9, 3, 4, 3};
  TestStruct testStruct(testArray);
  return 0;
}

添加。

我还发现了如何做到这一点,而无需像memmove()这样的额外 function :

#include <iostream>

void testFunc(const int (&array)[5])
{
  std::cout << array[0] << std::endl;
}

int main()
{
  testFunc({1, 2, 3, 4, 5});

  return 0;
}

暂无
暂无

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

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