سؤال

What I want to do is a bitwise XOR on two variables of the same struct in C++, i.e.

    D[i] ^= D[j];

where D is an Array containing strings, int, ....

However, the compiler complains (here using an integer array as index, meaning 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)))’

Does anyone have an idea how I can correct this line in order to achieve the bitwise XOR?

Any hints are very apreciated. Thanks in advance, cheers - alex

هل كانت مفيدة؟

المحلول

Overload the member in the struct:

struct X
{
   X& operator ^= (const X& other)
   {
       //...
       return *this;
   }
};

نصائح أخرى

It's a little tricky... you can either XOR by reinterpreting the structures as a contiguous area of data of an XOR-able type, or think about how to XOR each data member in turn. Both approaches have issues you'll need to consider, and which is best depends on why you're doing it.

For example:

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.
    }

Note that this xoring invalidates members like pointers and doubles - you shouldn't even read from them as those types unless you've xored again to restore the original values.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top