C++ 中有没有办法将 union/类/结构中的属性设置为默认属性?我使用 Visual Studio。 这个想法是能够访问它们而无需引用它。像这样的东西:
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 中。我认为这是不可能的,但可能有人知道一种方法。 谢谢!
不错的解决方案!
我正在尝试使用这个: union 位板{ t位板b; std::uint8_t [8];
Bitboard(tBitboard value = 0) { b = value; }
Bitboard& operator = (tBitboard value) { b = value; return *this; }
};
但是这一行有一个错误:
if (someBitboard)
错误 166 error C2451: 条件表达式无效
谢谢
最佳答案
您可以向 union 添加构造函数和运算符:
#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 union 中:
A union can have member functions (including constructors and destructors), but not virtual (10.3) functions.
注意:请注意有关值的内存布局(字节顺序)的平台依赖性。
关于c++类默认属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23357805/