0

I have been given an exercise that includes a lot of fiddling (looking at) with bits in a char[n].

I have to check some geometrical properties of a bit[n][8] obtained by taking each char, and splitting it into it's bits. I know that I can access bit[a] of the char c by doing something like c&((1<<8)>>n).

I would like to know if there is a way of making c[n] actually be c&((1<<8)>>n). I tried bool operator [](char c,int n); but that gave me this:

error: ‘bool operator[](char, int)’ must be a nonstatic member function
bool operator [](char c,int n);
Cœur
  • 37,241
  • 25
  • 195
  • 267
Mark Gardner
  • 442
  • 1
  • 6
  • 18

2 Answers2

3

As the error message says, operator[] must be a member function of a class or struct, and it must take one parameter. However, you can write a free named function (i.e. not an operator) to do what you want.

0

Here is a char wrapper class called Char. The two examples in main() demonstrate that you can use Char-typed values just like you would char values, except that Char has a [] operator, for getting its value's bit at some given index.

#include <iostream>

class Char {
    char c;
public:
    Char() = default;
    Char(const Char&) = default;
    Char(char src) : c(src) {}

    Char& operator = (char src) { c = src; return *this; }

    operator const char& () const { return c; }
    operator char& () { return c; }

    // Special [] operator
    // This is read-only -- making a writable (non-const)
    // version is possible, but more complicated.
    template <typename I>
    bool operator [](I bit_idx) const { return !!(c & (char(1) << bit_idx)); }
};

int main() {
    // Example 1
    // Initialize a new Char value, just like using char.
    Char my_char = 'x';
    // Math operators work as expected
    ++my_char;
    // And cout will produce the same output as a char value
    std::cout << "Bit 3 of '" << my_char << "' is ";
    // But unlike a char, the [] operator gives you
    // the bit at an index, as a bool value.
    std::cout << my_char[3] << "\n\n"; 

    //Example 2
    // Specify the Char type in a range-based for loop to
    // iterate through an array of char values, as Char values.
    const char str[] = "Tasty";
    for(Char ch : str) {
        // check if value is nonzero, the same as you would a char value
        if(ch) {
            // Send the value to cout,
            // cast to an int to see the ASCII code
            std::cout << ch << " (" << static_cast<int>(ch) << ") ";

            // Count down from bit 7 to 0 and use
            // the special [] operator to get each
            // bit's value.  Use this to output each
            // value's binary digits.
            for(int bit=7; bit>=0; --bit) {
                std::cout << ch[bit]; 
            }
            std::cout << '\n';
        }
    }
}

Output:

Bit 3 of 'y' is 1

T (84) 01010100
a (97) 01100001
s (115) 01110011
t (116) 01110100
y (121) 01111001
Christopher Oicles
  • 3,017
  • 16
  • 11