我有一个位字段结构,我想使用掩码对其执行逐位操作。我想知道最简单、最有效的方法。我尝试过使用转换运算符(这似乎是对两个结构执行&操作的低效方法),但我收到错误C2440:"type cast":无法从"const test::dtType"转换为"char"。没有用户定义的转换操作员可以执行此转换,或者该操作员不能称为
class test
{
public:
test() : startTime(0), endTime(5,23) {}
~test();
struct dtType {
// inline constructors with initialisation lists
dtType() {dtType(0);}
dtType(byte z) {dtType(z,z);}
dtType(byte n,byte h) : mins(n), hrs(h){}
// inline overloaded operator functions
operator char() {return mins + hrs<<3;}; // allow casting the struct as a char
// All I want to do is return (this & hrsMask == date & hrsMask)
// I know that in this trivial case I can do return (hrs == date.hrs) but I have simplified it for this example.
bool operator== (dtType date){return (char(this) & char(hrsMask)) == (char(date) & char(hrsMask));};
// data members
unsigned mins: 3; // 10's of mins
unsigned hrs: 5; // 8 bits
};
const static dtType hrsMask; // initialised outside the declaraion, since a static is not associated with an individual object.
dtType startTime; // initialised by test() in its initialisation list
dtType endTime; // initialised by test() in its initialisation list
};
// Typically in a source file, but can be in the header.
const test::dtType hrsMask(0,31);
我尝试过使用void指针来执行逐位操作。它可以编译,但我还没有测试过。
bool test::dtType::operator== (dtType date){
const void * longThisDT = this;
const void * longThatDT = & date;
const void * longMaskDT = & hrsMask;
return (*((long *)longThisDT) & *((long *)longMaskDT) == *((long *)longThatDT) & *((long *)longMaskDT));
};
这是我们能达到的效率吗?这需要三个额外的三分球,而我真正需要的只是一个长投。
首先花点时间准备WORKING示例,您的示例有很多错误:
-没有定义测试
-常量测试::dtType hrsMask(0,31)不正确,应为:const test::dtType test:hrsMask(0,31)
其他:
-您应该将运算符char(){更改为操作符char()const{-这正是编译器抱怨的内容:)
-不应该有字节mins:3而不是无符号mins:3吗?这实际上意味着"无符号int",所以它无论如何都使用4个字节
当this
被间接化并且常量被移除时,它就起作用:
bool operator== (dtType date) {
return (char(*this) & char(hrsMask)) == (char(date) & char(hrsMask));};
/* ... */
static dtType hrsMask;
/* ... */
test::dtType test::hrsMask(0,31);