如何通过引用传递类成员的固定大小数组?
我有一个包含固定大小数组的类节点。我还有另一个创建一个实例mynode的类,并调用一个函数,将5个值分配给数组中的字段。我想通过引用传递数组,以便该函数修改实际数组而不是副本,但我不知道如何修改。
节点:
class Node
{
public:
// Constructor, destructor, other members, etc
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;
}
int main()
{
Node *myNode = new Node();
doStuff(myNode->mArray);
// myNode->mArray is not modified
}
}
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. 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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,阵列已修改。一个最小可重现的示例:
这将打印预期:
如果您在功能中使用
node&
会更容易:虽然:Yes, the array is modified. A minimal reproducible example:
This prints the expected:
It'd be easier if you took a
Node&
in the function though:当通过参数中的值传递时,从不复制C风格数组。当作为普通参数传递时,它会变成指向第一个元素的指针。因此,您无需使用参考,只需使用普通的指针或数组参数即可。
A C-style array is never copied when passed by value in a parameter. 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.