コード例 #1
0
int main(int argc, char const *argv[])
{
	int count = 0
	Shape** shapes = randShapes(count);

	for (int i = 0; i < count; ++i)
	{
		//print
		if (typeid(*(shapes[i])) == typeid(Rectangle))
	    {
	         Rectangle *shape = dynamic_cast<Rectangle*>(shapes[i]);
	         shape->print();
	    }

		if (typeid(*(shapes[i])) == typeid(Circle))
	    {
	         Circle *shape = dynamic_cast<Circle*>(shapes[i]);
	         shape->print();
	    }
	}

	for (int i = 0; i < count; ++i)
	{
		delete shapes[i];
	}
	delete[] shapes;

	return 0;
}
コード例 #2
0
int main(void)
   {
   //Create vector shape with an initial size of 6
   std::vector <Shape *> shape(6);
   
   //Initialize vector with Shapes
   shape.push_back(new Circle("green", 10));
   shape.push_back(new Rectangle("red", 8, 6));
   shape.push_back(new Triangle("yellow", 8, 4));
   shape.push_back(new Triangle("black", 4, 10));
   shape.push_back(new Circle("orange", 5));
   shape.push_back(new Rectangle("blue", 3, 7));
   
  std::cout << std::endl << "Printing all shapes..." 
                         << std::endl << std::endl;
   
   //Process each element in vector 'shape'
   //'unsigned int' due to comparison warning
   for (unsigned int i = 0; i < shape.size(); ++i)
      {
	  Shape *shapePtr = dynamic_cast<Shape *> (shape[i]);
	  
	  if (shapePtr != 0)
	     shapePtr->print();
	 }
	  
   std::cout << std::endl << "Printing only circles..." 
                          << std::endl << std::endl;
   
   //'unsigned int' due to comparison warning
   for (unsigned int i = 0; i < shape.size(); ++i)
      {
	  Circle *circlePtr = dynamic_cast<Circle *> (shape[i]);
	  
	  if (circlePtr != 0)
	     circlePtr->print();  
	  }
	  
   //Loop through list of shape pointers and delete each object
   //Only needed if using ARRAY, not VECOTR.
  // for (unsigned int i = 0; i < shape.size(); ++i)
    // delete shape[i];
     
     std::cout << std::endl;
   
   return 0;
   }