2014-04-29 86 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。