/* File: box.C Final (?) implementation of class Box. */ #include #include #include #include #include #include "box.h" /* static (i.e., shared) members must be declared and initialized */ int Box::count = 0 ; /* Friend function */ int compare(Box A, Box B) { if (A.length < B.length && A.height < B.height && A.width < B.width) { return -1 ; } if (A.length > B.length && A.height > B.height && A.width > B.width) { return 1 ; } return 0 ; } /* the default constructor makes a new box with random dimensions. */ Box::Box() { printf("Debug: default Box constructor called\n") ; 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) { printf("Debug: alternate Box constructor called\n") ; if (count == 0) { /* first box? */ srand48( (long) time(NULL) ) ; /* set random seed */ } length = len ; height = ht ; width = wd ; count++ ; } /* print out the count field, etc. */ void Box::debug() { printf("number of boxes = %d\n", 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 ; }