简体   繁体   English

错误:预期为“;” 在“!”之前 代币

[英]Error: expected ';' before '!' token

// 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;
};

When I tried to get a better understanding of what an "iterator" is. 当我试图更好地理解“迭代器”是什么时。 I copy such code to my compiler (codeBlock). 我将此类代码复制到我的编译器(codeBlock)。 There is an error: "expected ';' 有一个错误:“ expected';” before '!' 在“!”之前 token". 令牌”。 What's the matter with that? 怎么了

You have a typo in operator!= : 您在operator!=有错字operator!=

p!rhs.p

should read 应该读

p != rhs.p

or, more generically, 或者,更笼统地说,

!(*this == rhs)

You also have an invalid empty character constant in this line: 此行中还有一个无效的空字符常量:

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

Looks like it's this line: 看起来是这样的:

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

Change it to this: 更改为此:

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

I suggest defining != as 我建议将!=定义为

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

So if == becomes more complicated you don't have to duplicate code in != 因此,如果==变得更加复杂,则无需在!=中重复代码。

Likewise you can define < > <= >= in terms of just < and ==, minimising code duplication 同样,您可以仅用<和==来定义<> <=> =,从而最大程度地减少代码重复

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);}

I believe it's in the overload for the != operator. 我相信这是!=运算符的重载。 The line should be: 该行应为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM