/* File: box2.C Another implementation of class Box. */ #include #include #include #include #include #include "box2.h" /* static (i.e., shared) members must be declared and initialized */ int Box::count = 0 ; /* the default constructor makes a new box with random dimensions. */ Box::Box() { if (count == 0) { /* first box? */ srand48( (long) time(NULL) ) ; /* set random seed */ } length = random() ; height = random() ; width = random() ; count++ ; } /* A second constructor with arguments */ Box::Box(float len, float ht, float wd) { if (count == 0) { /* first box? */ srand48( (long) time(NULL) ) ; /* set random seed */ } length = len ; height = ht ; width = wd ; count++ ; } /* Report vital stats */ void Box::identify() { if (length == 0.0 || height == 0.0 || width == 0.0) { printf("I am an invisible box\n") ; } else { printf("I am a box with length=%f, height=%f and width=%f\n", length, height, width) ; } } /* Compute box volume */ float Box::volume() { return length * height * width ; } /* Double each dimension */ void Box::grow() { length = length * 2 ; height = height * 2 ; width = width * 2 ; } /* Halve each dimension */ void Box::shrink() { length = length / 2 ; height = height / 2 ; width = width / 2 ; } /* return random value between 1.0 and 10.0 */ float Box::random() { double r ; r = drand48() * 9.0 + 1.0 ; return (float) r ; }