home *** CD-ROM | disk | FTP | other *** search
- Listing 2 - a crude application of the shape hierarchy in Listing 1
-
- //
- // 'clone_all' clones shape array 'sa1' with 'n'
- // elements
- //
- shape **clone_all(shape *sa1[], size_t n)
- {
- shape **sa2 = new shape *[n];
- for (size_t i = 0; i < n; ++i)
- sa2[i] = sa1[i]->clone();
- return sa2;
- }
-
- //
- // 'largest' returns the shape with the largest
- // area from shape array 'sa' with 'n' elements
- //
- shape *largest(shape *sa[], size_t n)
- {
- shape *s = 0;
- double m = 0;
- for (size_t i = 0; i < n; ++i)
- if (sa[i]->area() > m)
- {
- m = sa[i]->area();
- s = sa[i];
- }
- return s;
- }
-
- int main()
- {
- const int N = 4;
- shape *s[N];
- shape *ls;
- s[0] = new circle(shape::RED, 2);
- s[1] = new triangle(shape::BLUE, 5, 6, asin(0.8));
- s[2] = new rectangle(shape::RED, 3, 4);
- s[3] = new circle(shape::GREEN, 3);
- cout << "The shapes are:\n";
- for (int i = 0; i < N; ++i)
- cout << i << ")\t" << *s[i] << '\n';
- cout << '\n';
- shape **cs = clone_all(s, N);
- cout << "The cloned shapes are:\n";
- for (i = 0; i < N; ++i)
- cout << i << ")\t" << *cs[i] << '\n';
- cout << '\n';
- ls = largest(cs, N);
- cout << "The shape with the largest area is a...\n\t";
- cout << *ls << ".\n";
- cout << "Its area is " << ls->area() << ".\n";
- return 0;
- }
-