我遇到了C ++问题并创建了一个引用字节[]。
在C#中我的方法是:
public void customModuleFunctionsCheckedListBox_SelectedIndexChanged(object sender, EventArgs e)
{
//checks before calling this function if there is any element selected..
for (int i = 0; i < this.mainForm.customFunctionList[index].Items.Count; i++)
{
if (this.mainForm.customFunctionList[index].SelectedIndex == i)
{
this.mainForm.customFunctionUseCasesList[index].Items.Clear();
//this.mainForm.customFunctionUseCasesList[index].ItemsSourceOrWhateverMethodIs = aListOfStrings....
}
}
}
我想将其翻译为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
符号的一些内容,我尝试过这样的事情:
&
然后我得到错误:
&#39;缓冲区&#39;:引用数组是非法的。
那么如何更改我的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]);
}
}
但缓冲区没有变化。它的价值相同。
答案 0 :(得分:4)
如果你想通过引用传递数组,你应该
void SetBitAt(byte (buffer&)[10], int Pos, int Bit, bool Value)
但在你的情况下,你不需要那个,只是
void SetBitAt(byte buffer[], int Pos, int Bit, bool Value)
注意,在这种情况下,数组将衰减为指针(即byte*
),这意味着数组的大小不会被保留为引用传递。
答案 1 :(得分:1)
&#39;缓冲区&#39;:引用数组是非法的。
这是由于运营商的优先级。说byte &buffer[]
是一组引用,而byte (&buffer)[size]
是对数组的引用。
有关详细信息,请参阅C++ pass an array by reference。
那么如何更改我的C ++代码以使用参考数组呢?
将数组作为函数参数传递时,应删除&
符号。您仍然可以修改数组的内容,因为会传递数组的地址。
假设您有typedef
char
到byte
,您的功能签名应如下所示:
void SetBitAt(byte buffer[], int Pos, int Bit, bool Value) { ... }
请注意,上述内容相当于传递指针:
void SetBitAt(byte *buffer, int Pos, int Bit, bool Value) { ... }
修改数组的内容仍然是buffer[Pos] = // some value;
What is array decaying?上的这篇文章应该很有用。
答案 2 :(得分:0)
不应该只是这样:
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-th元素。这是普通的C,但它应该有用。
答案 3 :(得分:0)
您可以通过以下地址简单地传递:
void SetBitAt(byte* buffer, int Pos, int Bit, bool Value) { ... }
或简单地说:
void SetBitAt(byte buffer[], int Pos, int Bit, bool Value) { ... }
任何一个都会告诉编译器字节指针传递给函数,通过第二个头你省略指针算术;)