2012-07-17 57 views
0

我想要做的就是在C++相同結構的兩個變量,即位異或在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)))’ 

有沒有人有一個想法如何,我可以糾正這種爲了實現按位XOR?

任何提示是非常apreciated。在此先感謝,歡呼聲 - 亞歷

回答

3

超載在結構中的成員:

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

哇,這很快:)我會盡快嘗試,非常感謝! – astriffe 2012-07-17 09:43:23

+1

如果你想寫D [i]^D [j]那麼你可以重寫下一個運算符 - 'X運算符^(const X&b1,const X & b2);' – 2012-07-17 09:45:17

+0

謝謝Luchian你的答案!封裝的結構,其中一些我不應該觸摸,我會混合重載與執行異或操作的一些功能.. – astriffe 2012-07-17 10:22:23

1

這是一個有點棘手...您可以通過XOR重新解釋結構作爲XOR數據的連續區域或者考慮如何依次對每個數據成員進行異或運算。這兩種方法都有問題需要考慮,最好取決於你爲什麼這樣做。

例如:

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

注意,這個異或無效成員像指針和雙打 - 你甚至不應該從中讀出這些類型除非你再次異或以恢復原來的值。

+0

感謝@TonyDelroy您的答案!這正是一個問題,現在我卡住了 - 如何異或字符* []是不同的長度..我想短的一個只會在'缺少'位上有零位... – astriffe 2012-07-17 14:52:14

+0

順便說一句:在你的代碼中,它不是i ++和j ++嗎?這樣,你會從my_int_array [1]開始,這是第二個元素,不是嗎? – astriffe 2012-07-17 15:11:01

+0

@astriffe:它已經在循環增量語句中,而不是作爲XOR的副作用。 (討厭Sa fari沒有滾動條,但通常的雙指拖動工作)。 – 2012-07-17 22:06:56