2

マスクを使用してビット演算を実行したいビットフィールド構造体があります。これを行うための最も簡単で最も効率的な方法を知りたいです。変換演算子を使用してみましたが (2 つの構造体で & 操作を行うには非効率的な方法のようです)、エラー C2440: 'type cast' : cannot convert from 'const test::dtType' to '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));
};

これは私たちが得ることができるのと同じくらい効率的ですか?本当に必要なのは long へのキャストだけですが、これには 3 つの追加のポインターが含まれます。

4

2 に答える 2

0

まず最初に、WORKING サンプルの準備に時間をかけてください。あなたのものには多くのエラーがあります:
- ~test が定義されていません
- const test::dtType hrsMask(0,31); const test::dtType test:hrsMask(0,31);は正しくありません。

それ以外の場合:
- operator char() {operator char() const {に変更する必要があります -それがコンパイラが正確に愚痴をこぼすものです :) - unsigned mins: 3の代わりにバイト mins: 3
があるべきではありませんとにかく4バイトを使用するようにint'

于 2012-07-18T10:57:03.983 に答える
0

this間接的で const が削除されている場合に機能します。

bool operator== (dtType date) {
    return (char(*this) & char(hrsMask)) == (char(date) & char(hrsMask));};

/* ... */

static dtType hrsMask;

/* ... */

 test::dtType test::hrsMask(0,31);
于 2012-07-18T10:57:20.200 に答える