我想访问类实例的公共变量,其中实例保存在类类型的向量中。我必须使用迭代器来遍历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() {}
答案 0 :(得分:3)
首先将矩形添加到矢量,然后取消迭代迭代器并访问元素。
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;
}