【发布时间】:2021-06-13 22:43:21
【问题描述】:
我有以下 C++ 代码
矩形.h
class Rectangle {
public:
Rectangle(int _id);
void draw();
int getId();
private:
int id;
};
矩形.cpp
#include "Rectangle.h"
#include <iostream>
Rectangle::Rectangle(int _id) {
id = _id;
}
void Rectangle::draw() {
std::cout << "Drawing rectangle with id: " << id << std::endl;
}
int Rectangle::getId() {
return id;
}
矩形集合.h
#include "Rectangle.h"
class RectanglesCollection {
public:
Rectangle rectangle_00;
Rectangle rectangle_01;
Rectangle rectangle_02;
Rectangle rectangle_03;
RectanglesCollection();
void update();
};
矩形集合.cpp
#include "RectanglesCollection.h"
RectanglesCollection::RectanglesCollection() :
rectangle_00(10),
rectangle_01(20),
rectangle_02(30),
rectangle_03(40)
{}
void RectanglesCollection::update()
{
rectangle_00.draw();
rectangle_01.draw();
rectangle_02.draw();
rectangle_03.draw();
}
main.cpp
#include "Rectangle.h"
#include "RectanglesCollection.h"
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
RectanglesCollection rectangles;
rectangles.update();
std::cout << "Id of the first rectangle in collection of rectangles: " << rectangles.rectangle_00.getId() << std::endl;
return 0;
}
我的问题是,我是否有可能避免在 RectanglesCollection::update 方法中重复代码,而不是直接在单个 Rectangle 成员上方使用一些循环迭代?如果集合的用户除了定义Rectangle 类的实例之外不需要做任何其他事情,那将是理想的。同时,我想保留与 Rectangle 成员单独合作的可能性,例如 rectangles.rectangle_00.getId()。
【问题讨论】:
-
使用向量(如果元素的数量可以在运行时改变)或数组?
-
您通常会遍历数组或其他容器。只需将您的矩形放在某种容器中并循环它。
-
您正在寻找数组。
标签: c++ loops collections iteration