2017-02-15 1 views
0

私はchar[n]のビットでたくさんのバイディング(見て)を含む練習を与えられました。クラスを定義せずにcharの特定のビットにアクセスするために[]演算子をオーバーロードすることはできますか?

bit[n][8]の幾何学的特性を確認しなければなりません。各文字を取り、そのビットに分割します。 c&((1<<8)>>n)のようにすると、cbit[a]にアクセスできることがわかります。

実際にc[n]とする方法があるかどうかをご確認したいと思います。c&((1<<8)>>n)です。私はbool operator [](char c,int n);を試してみましたが、それは私にこれを与えた:

error: ‘bool operator[](char, int)’ must be a nonstatic member function 
bool operator [](char c,int n); 
+0

はする必要がありますが、私の質問は –

+2

何を達成するために 'のstd :: bitset'の使用について、その型には存在しない演算子*を使用して、まだ*についてですあなたが欲しいもの? –

+0

_なぜdownvotes?_私のものではなかったが、_研究の_がそれを説明するかもしれない。 –

答えて

3

エラーメッセージが言うように、オペレータは[]クラスまたは構造体のメンバ関数でなければならず、それは一つのパラメータを取る必要があります。ただし、自由に名前を付けた関数(つまり、演算子ではありません)を記述して、必要な処理を行うことができます。

+0

私は、機能が退屈であるという点に着目しました。しかし、大丈夫です。 –

+4

@Mark Writing関数はプログラミングが大事なものなので、興味深いものを見つけ出す方がいいでしょう。 –

+0

いいえ、プログラミングは注文をコンピュータに従わせることです。 –

0

ここには、Charと呼ばれるcharラッパークラスがあります。 main()の2つの例では、Charの値がcharの値と同じようにCharの値を使用できますが、Charには[]演算子があり、特定のインデックスでその値のビットを得ることができます。

#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'; 
     } 
    } 
} 

出力:Franç[email protected]

Bit 3 of 'y' is 1 

T (84) 01010100 
a (97) 01100001 
s (115) 01110011 
t (116) 01110100 
y (121) 01111001 
+0

うわー!ありがとう!私が機能を果たさなかったなら、これを使うでしょう。 –

関連する問題