我想要做的是对C ++中同一结构的两个变量进行按位异或,即
D[i] ^= D[j];
其中D是包含字符串的数组,int,....
然而,编译器抱怨(这里使用整数数组作为索引,意味着D [dInd [u]] ^ = ...):
Description Resource Path Location Type
no match for ‘operator^=’ in ‘*(D + ((long unsigned int)(((long unsigned int)
(*(dInd + ((long unsigned int)(((long unsigned int)u) * 4ul))))) * 2808ul)))
^= *(D + ((long unsigned int)(((long unsigned int)(*(dInd + ((long unsigned
int)(((long unsigned int)i) * 4ul))))) * 2808ul)))’
有没有人知道如何纠正这一行以实现按位异或?
任何提示都非常苛刻。在此先感谢,欢呼 - alex
答案 0 :(得分:3)
重载结构中的成员:
struct X
{
X& operator ^= (const X& other)
{
//...
return *this;
}
};
答案 1 :(得分:1)
这有点棘手......您可以通过将结构重新解释为XOR-able类型的连续数据区域来进行异或,或者考虑如何依次对每个数据成员进行异或。这两种方法都有你需要考虑的问题,哪种方法最好取决于你为什么要这样做。
例如:
struct X
{
X& operator^=(const X& rhs)
{
// WARNING: this won't follow pointers to "owned" data
unsigned char* p = (unsigned char*)this;
unsigned char* q = (unsigned char*)&rhs;
size_t size = sizeof *this;
while (size--)
*p++ ^= *q++;
}
};
v.s。
X& operator^=(const X& rhs)
{
my_int ^= rhs.my_int;
for (size_t i = 0; i < sizeof my_int_array / sizeof my_int_array[0]; ++i)
my_int_array[i] ^= rhs.my_int_array[i];
// WARNING: this won't XOR the string object's embedded data members -
// typically a pointer to the text, a size & capacity etc..
std::string::const_iterator j = rhs.my_string.begin();
for (std::string::iterator i = my_string.begin(); i != my_string.end() && j != rhs.my_string.end(); ++i, ++j)
*i ^= *j;
// note: you'll have to decide what to do for different-length string data, doubles etc.
}
请注意,此xoring会使指针和双精度等成员无效 - 您甚至不应将它们作为这些类型读取,除非您再次进行xored以恢复原始值。