[英]How can I pass a class member's fixed size array by reference?
I have a class Node that contains a fixed-size array.我有一个包含固定大小数组的类节点。 I have another class that creates an instance myNode and calls a function to assign 5 values to the fields in the array.我有另一个类,它创建一个实例 myNode 并调用一个函数来为数组中的字段分配 5 个值。 I want to pass the array by reference so the function modifies the actual array and not a copy, but I can't figure out how.我想通过引用传递数组,以便函数修改实际数组而不是副本,但我不知道如何。
Node:节点:
class Node
{
public:
// Constructor, destructor, other members, etc
uint8_t mArray[5];
}
Worker:工人:
class worker
{
void doStuff(uint8_t (&arr)[5])
{
arr[0] = 12;
arr[1] = 34;
arr[2] = 56;
arr[3] = 78;
arr[4] = 90;
}
int main()
{
Node *myNode = new Node();
doStuff(myNode->mArray);
// myNode->mArray is not modified
}
}
Yes, the array is modified.是的,数组被修改了。 A minimal reproducible example:一个最小的可重现示例:
#include <cstdint>
#include <iostream>
class Node {
public:
uint8_t mArray[5];
};
class worker {
void doStuff(uint8_t (&arr)[5]) {
arr[0] = 12;
arr[1] = 34;
arr[2] = 56;
arr[3] = 78;
arr[4] = 90;
}
public:
int main() {
Node *myNode = new Node();
doStuff(myNode->mArray);
for(auto v : myNode->mArray) {
std::cout << static_cast<unsigned>(v) << ' ';
std::cout << '\n';
}
delete myNode;
return 0;
}
};
int main() {
worker w;
return w.main();
}
This prints the expected:这会打印出预期的:
12 34 56 78 90
It'd be easier if you took a Node&
in the function though:但是,如果您在函数中使用Node&
会更容易:
#include <cstdint>
#include <iostream>
class Node {
public:
uint8_t mArray[5];
};
class worker {
void doStuff(Node& n) {
n.mArray[0] = 12;
n.mArray[1] = 34;
n.mArray[2] = 56;
n.mArray[3] = 78;
n.mArray[4] = 90;
// or just:
// n = Node{12,34,56,78,90};
}
public:
int main() {
Node *myNode = new Node();
doStuff(*myNode);
// ...
delete myNode;
return 0;
}
};
int main() {
worker w;
return w.main();
}
A C-style array is never copied when passed by value in a parameter.在参数中按值传递时,永远不会复制 C 样式的数组。 When passed as an ordinary argument, it decays into a pointer to the first element.当作为普通参数传递时,它衰减为指向第一个元素的指针。 So, you don't need to use a reference, just use an ordinary pointer or array parameter.因此,您不需要使用引用,只需使用普通的指针或数组参数即可。
class worker
{
void doStuff(uint8_t arr[5]) // same as uint8_t *arr
{
arr[0] = 12;
arr[1] = 34;
arr[2] = 56;
arr[3] = 78;
arr[4] = 90;
}
int main()
{
Node *myNode = new Node();
doStuff(myNode->mArray);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.