[英]How to work with the C++ class members individually and at the same time as a whole?
我有以下 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();
}
主文件
#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
class 的实例之外不需要做任何其他事情,那将是理想的。 同时,我想保留与 Rectangle 成员单独合作的可能性,例如rectangles.rectangle_00.getId()
。
如果您将 Rectangle 成员变量表示为 RectanglesCollection 中的std::array<Rectangle, 4>
,则可以通过索引和operator[](size_t)
访问器成员 function 轻松访问它们。
#include <array>
#include <cstddef>
#include <iostream>
#include <stdexcept>
using std::array;
using std::cout;
using std::ostream;
using std::out_of_range;
using std::size_t;
// NAME_OF for String-ify.
#define NAME_OF(x) #x
class Rectangle {
int _id;
public:
Rectangle(int id);
void draw(ostream&) const;
auto id() const -> int;
};
Rectangle::Rectangle(int id_) : _id{id_} { }
void Rectangle::draw(ostream& out) const {
out << "Drawing rectangle with id: " << id() << "\n";
}
auto Rectangle::id() const -> int {
return _id;
}
class RectanglesCollection {
array<Rectangle, 4> rectangles = {10, 20, 30, 40};
public:
auto operator[](size_t i) const -> Rectangle;
void display() const;
};
auto RectanglesCollection::operator[](size_t i) const -> Rectangle {
if (i >= rectangles.size())
throw out_of_range(NAME_OF(i));
return rectangles[i];
}
void RectanglesCollection::display() const {
for (auto&& r : rectangles) {
r.draw(cout);
}
}
int main() {
auto rectangles = RectanglesCollection();
rectangles.display();
cout << "Id of the first rectangle in collection of rectangles: " << rectangles[0].id() << "\n";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.