여기에 Char
이라는 char
래퍼 클래스가 있습니다. main()
의 두 예제는 Char
값이 특정 인덱스에서 값을 가져 오기 위해 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';
}
}
}
출력 :
Bit 3 of 'y' is 1
T (84) 01010100
a (97) 01100001
s (115) 01110011
t (116) 01110100
y (121) 01111001
FrançoisAndrieux는해야하지만, 내 질문 * –
해당 유형에 대한 존재하지 않는 연산자 *를 사용하는 방법에 대해 아직 @ 무엇을 달성하기 위해'표준 : bitset' 사용에 대한 뭘 원해? –
_ "왜 하향 투표장인가?"_ 내 것이 아니었지만 _ 연구가 부족했을 수 있습니다. –