c++类默认属性
c++ Class default property
c++中有没有办法将联合/类/结构中的属性设置为默认属性?我使用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人。b或
Board.by[3]=32;
以便在数组的字节3中放入32。我认为这是不可能的,但可能有人知道一种方法。谢谢
不错的解决方案!
我正在尝试使用这个:union Bitboard{t位板b;std::uint8_t by[8];
Bitboard(tBitboard value = 0) { b = value; }
Bitboard& operator = (tBitboard value) { b = value; return *this; }
};
但在这一行有一个错误:
if (someBitboard)
错误166错误C2451:条件表达式不是有效的
感谢
您可以向并集添加构造函数和运算符:
#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.
注意:请注意与值的内存布局(endianes)有关的平台依赖关系。
您可以重载=
运算符:
class C
{
public:
void operator = (int i)
{
printf("= operator called with value %dn", 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;
}
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 如何使用默认参数等选择模板专业化
- 具有默认模板参数的多态类的模板推导失败
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 初始化具有非默认构造函数的std::数组项的更好方法
- 修改"参数视图属性"面板 (5.7.0) 上的默认属性
- property_tree:无法设置默认属性值
- 成员属性作为方法的默认值
- 默认声明的属性?(状态设计模式)
- Visual Studio 2010 默认属性表似乎在调试和发布配置下都链接在一起,这是怎么回事?
- 使用类属性值作为方法默认参数的替代方法
- 是否有任何方法可以使用c++ libgraph为子图设置默认节点属性?
- 类初始化-属性没有默认构造函数
- c++中的默认实参有一些特殊的属性
- 如何获得RapidJSON模式来处理默认属性
- 属性类型未知的模板类中的默认构造函数
- c++类默认属性
- 错误C2512:没有合适的默认构造函数可用-如果在构造函数中初始化属性,为什么