2013-06-19 107 views
1

的是:什麼是枚舉類型的操作?

NSStreamEventOpenCompleted = 1 << 0 , 1 << 1 , 1 << 2 , 1 << 3 , 1 << 4 ? 

在下面的例子中

typedef enum { 
    NSStreamEventNone = 0, 
    NSStreamEventOpenCompleted = 1 << 0, 
    NSStreamEventHasBytesAvailable = 1 << 1, 
    NSStreamEventHasSpaceAvailable = 1 << 2, 
    NSStreamEventErrorOccurred = 1 << 3, 
    NSStreamEventEndEncountered = 1 << 4 
}; 

回答

1

這是一個bitwise shift操作。它被使用以便您可以從枚舉中設置一個或多個標誌。這個答案有一個很好的解釋:Why use the Bitwise-Shift operator for values in a C enum definition?

基本上,它是使一個整數能夠存儲與二進制和運營商進行檢查多個標誌。枚舉值最終看起來像這樣:

typedef enum { 
    NSStreamEventNone = 0,      // 00000 
    NSStreamEventOpenCompleted = 1 << 0,  // 00001 
    NSStreamEventHasBytesAvailable = 1 << 1, // 00010 
    NSStreamEventHasSpaceAvailable = 1 << 2, // 00100 
    NSStreamEventErrorOccurred = 1 << 3,  // 01000 
    NSStreamEventEndEncountered = 1 << 4  // 10000 
}; 

所以,你可以說:

// Set two flags with the binary OR operator 
int flags = NSStreamEventEndEncountered | NSStreamEventOpenCompleted // 10001 

if (flags & NSStreamEventEndEncountered) // true 
if (flags & NSStreamEventHasBytesAvailable) // false 

如果你沒有足夠的二進制移位,該值可能發生衝突或重疊,該技術不會工作。您還可以看到枚舉獲得設置爲0, 1, 2, 4, 8, 16,這是同樣的事情上面的轉變。

+1

其實'(旗&NSStreamEventNone)'是假的:-) –

+0

哦,非常好點!我會解決它。 –