簡體   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