I have a class, for example, Point
:
class Point {
public:
double x, y;
};
And I have some container, for example PointCloud
, that wraps inside std::vector<Point*>
:
class PointCloud {
public:
typedef std::vector<Point*>::const_iterator iterator;
iterator begin();
iterator end();
private:
std::vector<Point*> _point
};
Now I can use my class this way:
PointCloud cloud;
for(auto point : cloud) {
std::cout << point->x << std::endl;
}
I want to implement begin()
and end()
so my iterators return references instead of pointers and I could write my code that way:
PointCloud cloud;
for (auto point : cloud) {
std::cout << point.x << std::endl;
}
Note: operator .
instead of ->
operator
I have some reasons to do this thing:
compatibility: Firstly I write my class with
std::vector<Point> _point
and if I change my mind in the future and replace it withstd::vector<Point*> _point
and users of my class won't need to change something in their code.it's just safer to work with references.
There is no need to type
->
instead of.
.
I work with references instead of pointers.
Is it a right thing to do? An if yes, what would be the best way to implement it?
Aucun commentaire:
Enregistrer un commentaire