Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stdlib.h> //rand(), srand()
- #include <time.h> //time() for srand()
- #include <math.h> //sqrt()
- #include <sstream> //for convert double to string. std::ostringstream
- #define PI 3.1415926
- using namespace std;
- class figure {
- public:
- virtual double V()=0;
- virtual double S()=0;
- virtual void scale(double)=0;
- friend ostream& operator<<(ostream&,const figure&);
- //protected:
- virtual string show() const = 0;
- };
- ostream& operator<<(ostream& out, const figure&A) {
- out<<A.show();
- return out;
- }
- class ball: public figure {
- private:
- double r;
- string show() const {std::ostringstream ost; ost<<r; return "object Ball: r="+ost.str();}
- public:
- ball(double R=1.0): r(R) {}
- double V() {return 4*PI/3*r*r*r;}
- double S() {return 4*PI*r*r;}
- void scale(double k) {r*=k;}
- };
- class cone: public figure {
- private:
- double r,h;
- string show() const {std::ostringstream ost1,ost2; ost1<<r; ost2<<h; return "object Cone: r="+ost1.str()+"\th="+ost2.str();}
- public:
- cone(double R=1.0, double H=1.0): r(R), h(H) {}
- double V() {return PI*r*r*h/3;}
- double S() {return PI*r*(r+sqrt(r*r+h*h));}
- void scale(double k) {r*=k; h*=k;}
- };
- class cylinder: public figure {
- private:
- double r,h;
- string show() const {std::ostringstream ost1,ost2; ost1<<r; ost2<<h; return "object Cylinder: r="+ost1.str()+"\th="+ost2.str();}
- public:
- cylinder(double R=1.0, double H=1.0): r(R), h(H) {}
- double V() {return PI*r*r*h;}
- double S() {return 2*PI*r*(r+h);}
- void scale(double k) {r*=k; h*=k;}
- };
- figure* createObject(int x, double r=1.0, double h=1.0) {
- figure* p = NULL;
- switch(x) {
- case 0: p = new ball(r); break;
- case 1: p = new cone(r,h); break;
- case 2: p = new cylinder(r,h); break;
- }
- return p;
- }
- int main() {
- srand(time(NULL));
- const int N=5;
- figure *arr[N];
- cout<<"Create objects:"<<endl;
- for(int i=0; i<N; i++) {
- arr[i]=createObject(rand()%3,(rand()%9999)/100.0,(rand()%9999)/100.0);
- cout<<*arr[i]<<endl<<"Square: "<<arr[i]->S()<<"\tVolume: "<<arr[i]->V()<<endl<<endl;
- }
- cout<<endl<<"After scaling:"<<endl<<endl<<endl;
- for(int i=0; i<N; i++) {
- arr[i]->scale(0.1);
- cout<<*arr[i]<<endl<<"Square: "<<arr[i]->S()<<"\tVolume: "<<arr[i]->V()<<endl<<endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment