2017-02-15 1 views
0

나는 char[n]의 비트로 많은 (보고있는) 바이올린을 포함하는 연습을 받았다.[?] 연산자를 오버로드하여 클래스를 정의하지 않고 char의 특정 비트에 액세스 할 수 있습니까?

bit[n][8]의 일부 기하학적 특성을 확인하려면 각 문자를 가져 와서 비트로 분할해야합니다. c&((1<<8)>>n)과 같은 방법으로 c 문자 bit[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

FrançoisAndrieux는해야하지만, 내 질문 * –

+2

해당 유형에 대한 존재하지 않는 연산자 *를 사용하는 방법에 대해 아직 @ 무엇을 달성하기 위해'표준 : bitset' 사용에 대한 뭘 원해? –

+0

_ "왜 하향 투표장인가?"_ 내 것이 아니었지만 _ 연구가 부족했을 수 있습니다. –

답변

3

으로, 연산자 [] 클래스 또는 구조체의 멤버 함수이어야하며 하나 개의 매개 변수를해야합니다. 그러나 원하는 작업을 수행 할 수 있도록 무료로 명명 된 함수 (예 : 연산자가 아닙니다)를 작성할 수 있습니다.

+0

나는 기능이 지루한 지점에 이르렀다. 하지만 괜찮아. –

+4

@Mark Writing 함수는 프로그래밍에 관한 것이므로 흥미로워 야합니다. –

+0

아니요, 프로그래밍은 컴퓨터가 주문을 준수하도록하는 것입니다. –

0

여기에 Char이라는 char 래퍼 클래스가 있습니다. main()의 두 예제는 Char 값이 특정 인덱스에서 값을 가져 오기 위해 CharChar이있는 것을 제외하고는 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'; 
     } 
    } 
} 

출력 :

Bit 3 of 'y' is 1 

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

와우! 감사! 기능을 수행하지 않았다면 이것을 사용할 것입니다. –

관련 문제