[英]Understanding operator overloading & iterator why does it print out "wrhrwwr"?
在下面的代碼中,輸出是“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;
}
這將是更容易看到拉hophop
出的datas
類。 現在您可以看到hophop
構造函數以及它在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
。 然后它返回匹配之前的字符。 看看main里的評論。 返回e
之前的第一個字符和每個字符。
如果您沒有經常使用調試器,則應該使用。 通過在operator++
放置一個斷點,您可以看到發生了什么。
更新
我之前已經將++operator
的返回值設置為 void。 正如@JaMiT 指出的那樣,操作員返回*this
是合適的。 我還添加了兩個循環,它們應該比使用基於范圍的循環更清晰。 第三個例子實際上使用了++operator
的返回值,前兩個循環沒有。
並且,養成不using namespace std;
的習慣using namespace std;
它將使您免於遇到麻煩。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.