c++;类默认属性 在C++中有一种方法将一个属性在一个联合/类/结构中设置为默认的吗?我使用visualstudio。 这样做的目的是能够访问它们,而不必引用它们。比如: typedef uint64_t tBitboard; union Bitboard { tBitboard b; //modifier somewhere in this line to set as default uint8_t by[8]; }; Bitboard Board;
然后我想访问:c++;类默认属性 在C++中有一种方法将一个属性在一个联合/类/结构中设置为默认的吗?我使用visualstudio。 这样做的目的是能够访问它们,而不必引用它们。比如: typedef uint64_t tBitboard; union Bitboard { tBitboard b; //modifier somewhere in this line to set as default uint8_t by[8]; }; Bitboard Board;,c++,class,visual-c++,properties,C++,Class,Visual C++,Properties,然后我想访问: Board=100; 这意味着董事会有100人 或 因此,将32放入数组的字节3中。我认为这是不可能的,但可能有人知道一种方法。 谢谢 很好的解决方案 我试着用这个: 联合比特板{ TBITB板; std::uint8_t by[8] Bitboard(tBitboard value = 0) { b = value; } Bitboard& operator = (tBitboard value) { b = value; return *this;
Board=100;
这意味着董事会有100人
或
因此,将32放入数组的字节3中。我认为这是不可能的,但可能有人知道一种方法。
谢谢
很好的解决方案 我试着用这个: 联合比特板{ TBITB板; std::uint8_t by[8]
Bitboard(tBitboard value = 0) { b = value; }
Bitboard& operator = (tBitboard value) { b = value; return *this; }
};
但在这一行中有一个错误:
if (someBitboard)
错误166错误C2451:条件表达式无效
谢谢您可以重载
=
操作员:
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();
}
但在重载具有某些默认行为的运算符时要小心。您可能更容易使用您的类,但其他人更难跟上您的约定。如建议的那样,使用位移位运算符在这里是一个更好的主意
如果发布阵列,则可以自由访问其元素:
class C
{
public:
int b[5];
};
int main(int argc, char * argv[])
{
C c;
c.b[2] = 32;
}
您可以向联合添加构造函数和运算符:
#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;
}
注意:请注意与值的内存布局(endianess)相关的平台依赖性
#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;
}
A union can have member functions (including constructors and destructors), but not virtual (10.3) functions.