简体   繁体   中英

How to overload subscript operator with both read and write facility?

The following code is not compiling.

#include <bitset>
#include <iostream>

class Bits
{
public:
    std::bitset<4> bits;
public:
    Bits();
    Bits(Bits & b);
    Bits & operator = (Bits & b);
    bool   operator [] (int index) const; // For reading
    bool & operator [] (int index);       // For writing
};

Bits :: Bits() { }
Bits :: Bits(Bits & b)
{
    *this = b;
}

Bits &  Bits :: operator = (Bits & b)
{
    bits[0] = b.bits[0];
    bits[1] = b.bits[1];
    bits[2] = b.bits[2];
    bits[3] = b.bits[3];

    return *this;
}

bool Bits::operator [] (int index) const
{
   return bits[index];
}

bool & Bits::operator [] (int index)
{
   return bits[index];
}

int main()
{
    Bits bits;

    bits[0] = true;
    bits[1] = false;
    bits[2] = true;
    bits[3] = false;

    return 0;
}

Error:

1>------ Rebuild All started: Project: SubscriptOperatorOverloading, Configuration: Debug Win32 ------
1>Deleting intermediate and output files for project 'SubscriptOperatorOverloading', configuration 'Debug|Win32'
1>Compiling...
1>Bits.cpp
1>e:\developer-workspace\subscriptoperatoroverloading\subscriptoperatoroverloading\bits.cpp(39) : error C2440: 'return' : cannot convert from 'std::bitset<_Bits>::reference' to 'bool &'
1>        with
1>        [
1>            _Bits=4
1>        ]
1>Build log was saved at "file://e:\Developer-Workspace\SubscriptOperatorOverloading\SubscriptOperatorOverloading\Debug\BuildLog.htm"
1>SubscriptOperatorOverloading - 1 error(s), 0 warning(s)
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

Return std::bitset<4>::reference rather than bool& .

The reason std::bitset<4>::reference is not bool& is because (in a reasonable implementation) the elements of a bitset are computed values rather than objects; reading an element requires a computation and writing an element requires a computation, and thus the return value of operator[] cannot possibly be an ordinary reference.

Thus, bitset<N>::reference needs to be a proxy object; it is something that is convertible to bool (which does the correct calculation) and has an assignment operator (which does the correct calculation).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM