#include<iostream> using namespace std; class Box { public: Box(); Box(double lengthvalue,double breadthvalue,double heightvalue); double volume()const; int comparevolume(const Box& otherbox)const; int getobjectcount()const {return objectcount;} private: static int objectcount; double length; double breadth; double height; }; Box::Box() { cout<<endl<<"Default constructor called"<<endl; ++objectcount; length=breadth=height=1; } Box::Box(double lengthvalue,double breadthvalue,double heightvalue):length(lengthvalue), breadth(breadthvalue),height(heightvalue) { cout<<endl <<"constructor called" <<endl; ++objectcount; if(length<=0) length=1.0; if(breadth<=1.0) breadth=1.0; if(height<=0) height=1.0; } double Box::volume()const { return length*breadth*height; } int Box::comparevolume(const Box& otherbox)const { if(this->volume()<otherbox.volume()) return 1; else return 0; } int Box::objectcount=0; int main() { cout<<endl; Box firstbox(17.0,11.0,5.0); cout<<"object count is:"<<firstbox.getobjectcount()<<endl; Box boxes[5]; cout<<"objects count is:"<<firstbox.getobjectcount()<<endl; cout<<"volume of the first box="<<firstbox.volume()<<endl; const int count=sizeof boxes/sizeof boxes[0]; cout<<"The boxes array has "<<count<<"elements."<<endl; cout<<"Each element occupies"<<sizeof boxes[0]<<"bytes." <<endl; for(int i=0;i<count;i++) cout<<"volume of boxes["<<i<<"]="<<boxes[i].volume() <<endl; return 0; }

评论