2014-04-29 89 views
0

是否有C++的方式在聯盟/類/結構作爲一個默認設置的屬性?我使用Visual Studio。 這個想法是能夠訪問它們而不必引用它。喜歡的東西:C++默認類屬性

typedef uint64_t tBitboard; 

union Bitboard { 
    tBitboard b; //modifier somewhere in this line to set as default 
    uint8_t by[8]; 
}; 

Bitboard Board; 

然後,我要訪問:

Board=100; 

這使100在Board.b 或者

Board.by[3]=32; 

所以把32的字節3陣列。我認爲這是不可能的,但可能有人知道一種方式。 謝謝!


不錯的解決方案!

我試圖使用這一個: 聯合Bitboard { tBitboard b; std :: uint8_t [8];

Bitboard(tBitboard value = 0) { b = value; } 
    Bitboard& operator = (tBitboard value) { b = value; return *this;  } 
}; 

但在這一行有錯誤:

if (someBitboard) 

錯誤166錯誤C2451:條件表達式無效

感謝

回答

0

可以重載=操作:

class C 
{ 
public: 
    void operator = (int i) 
    { 
     printf("= operator called with value %d\n", i); 
    } 
}; 

int main(int argc, char * argv[]) 
{ 
    C c; 
    c = 20; 

    getchar(); 
} 

重載操作符時要小心,它有一些默認行爲。你可能會更容易地使用你的課程,但更難讓其他人跟上你的習慣。使用位移運算符 - 如Bgie建議的 - 在這裏是一個更好的主意。

如果發佈一個數組,你可以自由訪問它的元素:

class C 
{ 
public: 
    int b[5]; 
}; 

int main(int argc, char * argv[]) 
{ 
    C c; 
    c.b[2] = 32; 
} 
1

您可加入建設者和運營商工會:

#include <iostream> 
#include <iomanip> 

typedef std::uint64_t tBitboard; 

union Bitboard { 
    tBitboard b; 
    std::uint8_t by[8]; 

    Bitboard(tBitboard value = 0) { b = value; } 
    Bitboard& operator = (tBitboard value) { b = value; return *this; } 
    std::uint8_t& operator [] (unsigned i) { return by[i]; } 
}; 

int main() 
{ 
    // Construct 
    Bitboard Board = 1; 
    // Assignment 
    Board = tBitboard(-1); 
    // Element Access 
    Board[0] = 0; 

    // Display 
    unsigned i = 8; 
    std::cout.fill('0'); 
    while(i--) 
     std::cout << std::hex << std::setw(2) << (unsigned)Board[i]; 
    std::cout << '\n'; 
    return 0; 
} 

這是覆蓋在9.5工會:

A union can have member functions (including constructors and destructors), but not virtual (10.3) functions. 

注:請有關VALU的內存佈局(字節序)感知平臺的依賴性ES。