Table Of Contents

Previous topic

7.5. Moving a shape

Next topic

7.7. Implementing a new polygon shape

Download

7.6. Operators overloading

spot

Reading/writing shapes via operator overloading. Heed towards the presentation about the operators overloading

Have a look at the include/boundingbox.h header file which holds the definition of the BoundingBox for each shape, and in which a few operators have been already defined. Overload the << and >> operators in the Shape and BoundingBox classes so they can be used to read/write shapes.

Note

You need to replace the methods Shape::Read(std::ifstream &f) and Shape::Save(std::ofstream &f) using the corresponding overloaded operator. But the reading of the SHAPE, TYPE (and perhaps SHAPE_END) keywords – which describe the structure of the file – will stay in Selection::Read(std::ifstream &f).

The WIDTH, HEIGHT and ORIGIN keywords – which describe the data layout – will now be read in the BoundingBox class. The Shape::Read(std::ifstream &f) method will thus contain only the bare minimum (i.e. a few lines...)

The goal of this step is to delegate as best as possible the data handling to the class which manages those data – i.e. BoundingBox.

You should add a method const std::string& BoundingBox::isValid() const to handle errors. This method should return "" (an empty string) when everything is OK or your error message otherwise.

The prototypes of the methods to be overloaded are below:

/**
 * @brief output operator overload (shapes output format)
 * @param os : output fstream
 * @param sh : shape to save 
 */
friend std::ofstream& operator<<(std::ofstream& os, const Shape* sh);

/**
 * @brief input operator overload (shapes input format)
 * @param is : input fstream
 * @param sh : shape to display
 */
friend std::ifstream& operator>> (std::ifstream& is, Shape* sh);


/**
 * @brief output operator overload (boundingbox output format)
 * @param os : output fstream
 * @param bo : boundingBox to save
 */
friend std::ofstream& operator<<(std::ofstream& os, const BoundingBox& bo);
                    
/**
 * @brief input operator overload (boundingbox input format)
 * @param is : input fstream
 * @param bo : boundingBox to save
 */
friend std::ifstream& operator>> (std::ifstream& is, BoundingBox& bo);

Warning

  • notice the friend keyword. This keyword allows to grant wider access to parts of the internals of a class to a function or to another class. In the .cpp source file, this keyword shouldn’t appear in the declaration (nor in the definition) of the functions.
  • notice how the Shape class is passed by-address and how the BoundingBox class is passed by-reference.
../_images/validate-step1.jpg

Validate this step