了解运算符重载和迭代器,为什么它会打印出"wrhrwwr"?

Understanding operator overloading & iterator why does it print out "wrhrwwr"?

本文关键字:打印 wrhrwwr 为什么 重载 运算符 迭代器 了解      更新时间:2023-10-16

在下面的代码中,输出是"wrhrwwr",我试图理解迭代器在做什么,以及"++"是如何重载的。似乎它以某种方式跳过了"e"。但是,代码对我来说很不清楚,也许我可以得到帮助。 谢谢

#include <iostream> 
using namespace std;
class datas {
private: 
const char *string,marker;
const int len;
public:
class hophop {
private:
const char *pos, next;
public: 
char operator *() { return *pos; }
hophop operator ++() {++pos;while (*(pos+1)!=next)  ++pos; return *this; }
bool operator !=(hophop &o) { return pos < o.pos; }
hophop(const char *p, char m) : pos(p),next(m) {}
};
typedef hophop iterator;
iterator begin() { return hophop (string, marker); }
itrator end () { return hophop(string +len ,marker); }
datas(const char *d,int l, char m) : string (d), len(l),marker(m){}
};
int main( void ) {
datas chars ("we are where we were", 20, 'e');
for (char c: chars)
cout << c;
return 0;
}

hophopdatas类中拉出会更容易看到。现在,您可以看到hophop构造函数及其用途。我会删除++operator的返回值,将其设置为 void,以指出它在这里没有任何作用。

#include <iostream> 
class hophop {
private:
const char* pos, next;
public:
hophop(const char* p, char m) : pos(p), next(m) {}
char operator *() { return *pos; }
hophop operator ++() {
++pos;
while (*(pos + 1) != next)
++pos;
return *this;
}
bool operator !=(const hophop& o) { return pos < o.pos; }
};
class datas {
private:
using iterator = hophop;
const char* string, marker;
const int len;
public:
datas(const char* d, int l, char m) : string(d), len(l), marker(m) {}
iterator begin() { return hophop(string, marker); }
iterator end() { return hophop(string + len, marker); }
};
int main(void) {
datas chars("we are where we were", 20, 'e');
//           w   r   h r  w  w r
for (char c : chars)
std::cout << c;
std::cout << "nusing a non range based for loop:"  << std::endl;
for (hophop it = chars.begin(); it != chars.end(); ++it)
std::cout << *it;
std::cout << "nor where the return value could be used:" << std::endl;
auto it = chars.begin();
std::cout << *it;
for (; it != chars.end();)
std::cout << *++it;
}

所以现在可能更容易看到 hophop ++ 运算符是如何工作的。operator *()在循环开始时被调用,因此无论第一个字符是什么,它都会被检索。然后调用++operator,它将迭代器至少向前移动一次,直到它与next匹配。然后它返回匹配前的字符。主要查看评论。返回e之前的第一个和每个字符。

如果您没有经常使用调试器,您应该这样做。 通过在operator++中放置断点,您可以看到正在发生的事情。

更新

我之前已将++operator的返回值设置为 void。正如@JaMiT指出的那样,操作员返回*this是合适的。我还添加了另外两个循环,它们应该比使用基于范围的循环更清晰。第三个例子实际上使用了++operator的返回值,前两个循环没有。

而且,养成不using namespace std;的习惯 这将使您免于未来的麻烦。