c++ - 错误 : expected ';' before '!' token

标签 c++

// 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)。 有一个错误:“预期';'前 '!' token ”。 这是怎么回事?

最佳答案

您在 operator!= 中有错字:

p!rhs.p

应该阅读

p != rhs.p

或者,更一般地说,

!(*this == rhs)

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

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

关于c++ - 错误 : expected ';' before '!' token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19710253/

相关文章:

c++ - C++中的全局变量内存分配

c++ - 晚期默认模板参数声明的 clang++ 错误

c++ - 初始化静态成员使编译工作......但是为什么

c++ - 复制省略和临时绑定(bind)引用对象

C++ 内存缓存库

c++ - 在基于 Visual Studio MFC 的应用程序中禁用事件处理程序

c++ - OpenGL,C++,为什么 glutReshapeFunc 函数给出黑色 opengl 屏幕?

c++ - 使用 PCL 从点云中提取点

c++ - if 语句总是执行

c++ - 为什么包含 char、short 和 char(按此顺序)的结构在启用 4 字节打包的 C++ 中编译时会变成 6 字节结构?