我正在尝试使用位字段来存储一系列用于制作图形三角形的计数器,因为我只需要其中一些计数器的值 0,1,2 并且不想浪费内存。代码应该做的是从 bf.vertIndex = 0 开始,然后循环直到 bf.vertIndex = 6 为止,它将停止运行。然而,该程序会导致无限循环,当我将 bf.vertIndex 的值打印为 int 时,它始终 = 1。我是否可以对这些操作数使用位字段?我可以将一个整数(例如 2)添加到给定位字段的值中吗?
float vertexData[12];
triInfo bf;
count = 0;
bf.trinum = 0;
bf.addedx = 0;//tracks if the x cord needs to be offset = 1 or 0
bf.addedy = 0;//same as for the x cord
bf.vertIndex = 0;
//this loop should make a triangle
while (bf.vertIndex < 6){
//sets cordinates for a vertex
vertexData[bf.vertIndex] = 500 + width*(bf.addedx);
vertexData[bf.vertIndex] = 500 + height*(bf.addedy);
//keeps track of the number of vertices created and checks where if an
bf.vertIndex += 2;
if (bf.vertIndex = 2 && bf.trinum == 0){
bf.addedy = !bf.addedy;
}
if (bf.vertIndex = 4 && bf.trinum == 0){
bf.addedx = !bf.addedx;
}
cout << ((int)bf.vertIndex);
}
这是我使用的位域的布局方式
struct triInfo
{
unsigned char trinum:1, addedx :1,addedy:1, vertIndex:5;
};
我在这里看到了一个教程Youtube制作视频的绅士将两个值相加在一起,并在视频中的 10:15 点以字符形式存储。
最佳答案
您可以将位字段与 <
进行比较, >
,和 ==
,就像任何其他整数一样。但是=
是一个赋值,而不是一个比较,并且您无意中覆盖了您尝试比较的值。
如果您使用 clang 或 GCC,您应该养成使用 -Wall
进行编译的习惯启用编译器警告,然后仔细阅读警告,以便能够修复根本原因。 (其他编译器也有类似的机制;请参阅手册。)
关于c++ - 可以使用 <、>、= 比较双字段吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46518274/