错误:令牌之前的预期';' '!'
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;
};
当我试图更好地理解什么是"迭代器"时。我将此类代码复制到我的编译器(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;}
相关文章:
- holeMenuProgram.cpp:38:1 错误:'}'令牌之前的预期主表达式
- Arduino 用于语句错误。令牌之前的预期')' ';'。如何解决这个问题?
- 错误:令牌 { '{' 之前应存在非限定 ID
- "错误 C0000:语法错误,令牌"<EOF>"处出现意外$end,并且不确定
- (错误:令牌之前'<<'预期的主表达式)
- 令牌 C++ 错误之前'['非限定 ID
- 修复令牌错误之前';'预期的非限定 ID
- 是什么导致了构造函数之后的这些"意外令牌"错误?
- 插入protobuf时SQLite无法识别的令牌错误:要处理哪些令牌以及如何处理?
- 获取语法和意外令牌错误,任何人都知道原因
- 令牌"("错误之前缺少 QT 二进制运算符
- 声明cudaError_t变量时出现无法识别的令牌错误
- CFtpConnection::GetCurrentDirectory未解析的令牌错误.不过,像SetCurrentDi
- 令牌错误之前"{"预期类名
- 令牌错误之前的预期主表达式'<'
- “{”令牌错误前预期的非限定id
- 令牌错误之前'{'预期类名
- 文件RecvFile函数中预期的令牌错误
- 令牌错误之前应为不合格的id
- Visual Studio 2010 + CUDA 4:尝试使用NPP分配内存时出现无法识别的令牌错误