Let's say we have a class hierachy:
class DrawingObject{
protected:
std::string name;
int x1, y1;
int x2, y2;
public:
DrawingObject();
DrawingObject(const std::string& name, int x1, int y1, int x2, int y2);
DrawingObject(const DrawingObject& obj);
DrawingObject& operator=(const DrawingObject& rhs);
virutal ~DrawingObject();
virtual void Draw()const;
};
void DrawingObject::Draw()const
{
std::cout<<"I am a Base object named "<<name
<<", I don't konw how to draw myself!" <<std::endl;
}
class Rectangle : public DrawingObject
{
public:
Rectangle(const std::string& name, int x1, int y1, int x2, int y2)
: DrawingObject(name, x1, y1, x2, y2);
virtual void Draw()const;
};
void Rectangle::Draw()const
{
std::cout<<"I am a Rectangle object named "<<name
<<", topLeft("<<x1<<", "<<y1<<"); bottomRight ("
<<x2<<", "<<y2<<std::endl;
}
class Line : public DrawingObject
{
public:
Line(const std::string& name, int x1, int y1, int x2, int y2)
: DrawingObject(name, x1, y1, x2, y2);
virtual void Draw()const;
};
void Line::Draw()const
{
std::cout<<"I am a Line object named "<<name
<<", from("<<x1<<", "<<y1<<"); to ("
<<x2<<", "<<y2<<std::endl;
}
Above code is just to demonstrate the output format, feel free to redesign the class hierachy or add new members (eg, flag), as long as you keep the 3 classes and implement the Draw() method.
Then 100 objects (of 1 of the 3 classes) will be generated randomly and be push_back'ed (the actual object instead of a pointer to it will be stored) into a std::vector<DrawingObject> container. Finally, iterate through the objects and invoke Draw() on each of them.
Please put all your code together (do not use a separate header file) and paste it within a code tags so that it can be tested easily. Compile and run you program before posting.
Thanks, Lance


Sign In
Create Account


Back to top









