如何访问向量迭代器中的 class 变量?

How to access class variable inside a vector iterator?

我想访问 class 实例的 public 变量,其中实例保存在 class 类型的向量中。我必须 运行 使用迭代器遍历 vector 的所有元素,但是对于如何使用迭代器获取变量这让我感到困惑。我正在使用 C++98。

source.cpp:

#include <iostream>
#include <vector>
#include "Rectangle.h" 

using namespace std;

int main() {    
    int len = 2, hen = 5;   
    int len2 = 4, hen2 = 10;

    Rectangle rect1(len, hen);  
    Rectangle rect2(len2, hen2);        
    vector<Rectangle> Rects;
    Rects.push_back(rect1);
    Rects.push_back(rect2);

    for (std::vector<Rectangle>::iterator it = Rects.begin(); it != Rects.end(); ++it) {        
       //how to access length and height here?  
    }

    system("pause");    
    return 0; 
}

Rectangle.h:

#pragma once
class Rectangle
{
private:        

public:
    int length;
    int height;

    Rectangle(int& length, int& height);
    ~Rectangle();
};

Rectangle.cpp:

#include "Rectangle.h"

Rectangle::Rectangle(int& length, int& height) 
    : length(length), height(height)
{ }

Rectangle::~Rectangle() {}

首先将矩形添加到 vector,解引用迭代器并访问元素。

int main() {    
    int len = 2, hen = 5;   
    int len2 = 4, hen2 = 10;

    Rectangle rect1(len, hen);  
    Rectangle rect2(len2, hen2);        
    vector<Rectangle> Rects;
    Rects.push_back(rect1);
    Rects.push_back(rect2);

    for (std::vector<Rectangle>::iterator it = Rects.begin(); it != Rects.end(); ++it) {        
       std::cout << "length " <<(*it).length<<std::endl;
       std::cout << "height " <<(*it).height<<std::endl;
    }

    system("pause");    
    return 0; 
}