C++引用字节数组

C++ reference byte array

本文关键字:数组 字节数 字节 引用 C++      更新时间:2023-10-16

我在C++和创建引用字节[]时遇到问题。

在C#中,我的方法是:

public static void SetBitAt(ref byte[] Buffer, int Pos, int Bit, bool Value)
    {
        byte[] Mask = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
        if (Bit < 0) Bit = 0;
        if (Bit > 7) Bit = 7;
        if (Value)
            Buffer[Pos] = (byte)(Buffer[Pos] | Mask[Bit]);
        else
            Buffer[Pos] = (byte)(Buffer[Pos] & ~Mask[Bit]);
    }

我想把它翻译成C++,但我无法让ref为C++工作。我看到了一些关于&符号的东西,我尝试了这样的东西:

void SetBitAt(byte& buffer[], int Pos, int Bit, bool Value)
{
    byte Mask[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
    if (Bit < 0) Bit = 0;
    if (Bit > 7) Bit = 7;
    if (Value)
    {
        buffer[Pos] = (byte)(buffer[Pos] | Mask[Bit]);
    }
    else
    {
        buffer[Pos] = (byte)(buffer[Pos] & ~Mask[Bit]);
    }
}

但是我得到错误:

"buffer":引用数组是非法的。

那么,如何更改C++代码以使用引用数组呢?

编辑:我用这个方法来设置缓冲区,但当我使用这个方法时,它不会改变。

其他类别:

buffer = ReadDB(2);          //Read the values in the DataBlock
SetBitAt(buffer, 0,0 true);  //Set bit 0,0 to 1(true)
WriteDB(2, buffer);          //Write the values to the Datablock

但是缓冲区不会改变。其值相同。

如果你想通过引用传递数组,你应该

void SetBitAt(byte (buffer&)[10], int Pos, int Bit, bool Value)

但在你的情况下,你不需要它,只需要

void SetBitAt(byte buffer[], int Pos, int Bit, bool Value)

注意,在这种情况下,数组将衰减为指针(即byte*),这意味着数组的大小不会像传递引用那样保留。

"buffer":引用数组是非法的。

这是由于操作员的优先级。说byte &buffer[]是引用的数组,而说byte (&buffer)[size]是对数组的引用。

有关更多详细信息,请参阅C++通过引用传递数组。

那么,如何更改C++代码以使用引用数组呢?

当将数组作为函数参数传递时,应该去掉&符号。您仍然可以修改数组的内容,因为会传递数组的地址。

假设你有一个charbytetypedef,你的函数签名应该是这样的:

void SetBitAt(byte buffer[], int Pos, int Bit, bool Value) { ... }

请注意,以上相当于传递一个指针:

void SetBitAt(byte *buffer, int Pos, int Bit, bool Value) { ... }

修改数组的内容仍然是说buffer[Pos] = // some value; 的问题

这篇关于什么是数组衰减的帖子?应该是有用的。

它不应该简单地像这样吗:

void SetBitAt(byte buffer[], int Pos, int Bit, bool Value)
{
    byte Mask[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
    if (Bit < 0) Bit = 0;
    if (Bit > 7) Bit = 7;
    if (Value)
    {
        buffer[Pos] = (byte)(buffer[Pos] | Mask[Bit]);
    }
    else
    {
        buffer[Pos] = (byte)(buffer[Pos] & ~Mask[Bit]);
    }
}

通过这种方式,缓冲区作为指针传递,缓冲区[Pos]引用缓冲区的第Pos个元素。它是普通的C,但应该有效。

您可以简单地通过地址将其传递为:

void SetBitAt(byte* buffer, int Pos, int Bit, bool Value) { ... }

或者简称为:

void SetBitAt(byte buffer[], int Pos, int Bit, bool Value) { ... }

任何一个都会告诉编译器字节指针被传递给函数,或者通过第二个标头可以省略指针算法;)