错误:令牌之前的预期';' '!'

Error: expected ';' before '!' token

本文关键字:令牌 错误      更新时间:2023-10-16
// std:: iterator sample
#include <iostream>  // std::cout
#include <iterator>  // std::iterator, std::input_iterator_tag
class MyIterator:public std::iterator<std::input_iterator_tag, int>
{
int *p;
public:
MyIterator(int *x):p(x){}
MyIterator(const MyIterator& mit):p(mit.p){}
MyIterator& operator++(){++p; return *this;}
MyIterator operator++(int){MyIterator tmp(*this);operator++(); return tmp;}
bool operator==(const MyIterator& rhs){return p == rhs.p;}
bool operator!=(const MyIterator& rhs){return p!rhs.p;}
int& operator*(){return *p;}
};
int main(){
int numbers[] = {10, 20, 30, 40, 50};
MyIterator from(numbers);
MyIterator until(numbers+5);
for (MyIterator it=from; it!=until; it++)
std::cout << *it << '';
std::cout << 'n';
return 0;
};

当我试图更好地理解什么是"迭代器"时。我将此类代码复制到我的编译器(codeBlock)中。有一个错误:"在'!'令牌之前有预期的';'"。这是怎么回事?

您在operator!=中有拼写错误:

p!rhs.p

应改为

p != rhs.p

或者,更一般地说,

!(*this == rhs)

此行中还有一个无效的空字符常量:

std::cout << *it << '';
                    ^^  // Get rid of that, or change it to something sensible

看起来像是这一行:

bool operator!=(const MyIterator& rhs){return p!rhs.p;}

将其更改为:

bool operator!=(const MyIterator& rhs){return p != rhs.p;}

我建议将 != 定义为

bool operator==(const MyIterator& rhs){return p == rhs.p;}
bool operator!=(const MyIterator& rhs){return !(*this == rhs);}

因此,如果 == 变得更加复杂,您不必在 != 中复制代码

同样,您可以仅根据 <和 定义="><> <=>=,从而最大限度地减少代码重复

bool operator == (const MyIterator& rhs) const {return p == rhs.p;}
bool operator <  (const MyIterator& rhs) const {return p < rhs.p;}
bool operator <= (const MyIterator& rhs) const {return (*this == rhs) || (*this < rhs);}
bool operator != (const MyIterator& rhs) const {return !(*this == rhs);}
bool operator >= (const MyIterator& rhs) const {return !(*this < rhs);}
bool operator >  (const MyIterator& rhs) const {return !(*this <= rhs);}

我相信这是!=运算符的重载。 该行应为:

bool operator!=(const MyIterator& rhs){return p!=rhs.p;}