我有一个简单的Vector类,实现了索引操作符.来自这个和其他相关问题,我不确定为什么以下代码编译:
int main()
{
const Vector A(5);
cout << "A :" << A << endl;
A[0] = 5;
cout << "A: " << A << endl;
}
Run Code Online (Sandbox Code Playgroud)
Vector.h
#pragma once
#include <iostream>
#include <functional>
namespace vector
{
class Vector
{
friend std::ostream& operator<<(std::ostream&, const Vector&);
int n;
int *arr;
public:
Vector(int = 0);
~Vector();
Vector(const Vector&);
Vector& operator=(const Vector&);
private:
void copy(const Vector&);
public:
int& operator[](const int) const;
};
}
Run Code Online (Sandbox Code Playgroud)
Vector.cpp
#include "Vector.h"
#include <algorithm>
#include …Run Code Online (Sandbox Code Playgroud) 据我所知,迭代器是一种为客户端提供接口的机制,用于观察/迭代/传递例如自定义集合的内容,而不会破坏信息隐藏原则.STL容器有自己的迭代器,所以我们可以使用for ( : )和for_each循环它们没有问题.
我的问题最初是:为什么要继承std::iterator?与以下示例相比,它提供了哪些附加功能:
SimpleArray.h
class SimpleArray
{
int *arr;
int n;
public:
explicit SimpleArray(int = 1);
~SimpleArray();
friend ostream& operator<<(ostream&, const SimpleArray&);
friend istream& operator>>(istream&, SimpleArray&);
// encapsulated "iterator"
class Observer
{
int *p;
public:
Observer(int *value = nullptr) : p(value) {}
Observer& operator++() { p++; return *this; }
Observer operator++(int) { int *temp = p; p++; return Observer(temp); }
bool operator==(Observer other) const { return p == other.p; }
bool operator!=(Observer …Run Code Online (Sandbox Code Playgroud)