是否可以超载[]运算符在不定义类的情况下访问特定的字符
Is it possible to overload the [] operator to access a specific bit of a char without defining a class?
我得到了一个练习,其中包括大量的 char[n]
中带有位的摆弄(看)。
我必须检查通过取每个char获得的bit[n][8]
的一些几何特性,然后将其拆分为块。我知道我可以通过执行诸如c&((1<<8)>>n)
之类的事情来访问char c
的bit[a]
。
我想知道是否有一种使c[n]
实际上 be 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);
正如错误消息所说,操作员[]必须是类或结构的成员函数,并且必须采用一个参数。但是,您可以编写一个免费的命名函数(即不是操作员)来完成您想要的事情。
这是一个名为 Char
的 char
包装程序类。main()
中的两个示例表明,您可以像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] << "nn";
//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
相关文章:
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 是否可以在不复制的情况下访问undered_map中的元素
- 为什么不能指向指针,在没有强制转换的情况下访问结构成员?
- 为什么可以在没有实例变量的情况下访问静态回调方法中的静态成员变量?
- 如何在不设置完整路径的情况下访问 c++ 中的资源
- 如何在 getter 的父类中初始化变量的情况下访问子类中的变量
- 在不违反严格的别名规则的情况下访问进程间共享内存中的对象
- C++ 在不打开文件的情况下访问IMAGE_OPTIONAL_HEADER64?
- 如何在不使用全局变量的情况下访问 lambda 中的变量
- C++是否提供了一种在没有范围解析运算符的情况下访问类中的类的方法?
- 是否可以超载[]运算符在不定义类的情况下访问特定的字符
- 在没有捕获列表的情况下访问 lambda 中的变量
- 如何在不注册对象的情况下访问标准项模型的数据?
- 在不破坏封装的情况下访问基类元素
- 如何在不将类数据成员作为参数传递的情况下访问线程中的类数据成员
- 如何在没有 A 全局的情况下访问 A::member()
- 在不知道名称的情况下访问函数参数
- 在不破坏封装的情况下访问替代功能
- 在多继承编译器的情况下访问成员变量是否依赖?如何正确地做
- 在没有位置的情况下访问违规读取位置