Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Zdefiniuj klase bazową Bryła oraz pochodne Sześcian i Kula.
- Uwzględnij polimorficzną metodę obliczającą objętość.
- Napisz program obliczający średnią objętość brył w danej kolekcji vector<Bryła*>*/
- #include <iostream>
- #include <vector>
- #define PI 3.14
- #include <time.h>
- #include <stdlib.h>
- using namespace std;
- class Bryla{
- public:
- virtual double volume()=0;
- };
- class Szescian : public Bryla{
- private:
- double s;
- public:
- Szescian (double s1):s(s1){}
- double volume(){
- return s*s*s;
- }
- };
- class Kula:public Bryla{
- private:
- double r;
- public:
- Kula(double r1):r(r1){}
- double volume(){
- return 4/3*PI*r*r*r;
- }
- };
- double meanVolume(vector <Bryla*> v){
- vector <Bryla*>:: iterator it =v.begin();
- double sum=0;
- while(it != v.end()){
- sum+=(*it)->volume();
- it++;
- }
- return sum/v.size();
- }
- void fillCollection(vector <Bryla*> & v, int n){
- for(int i=0; i<n; i++){
- switch(rand()%2+1){
- case 1:
- v.push_back(new Szescian(rand()%5+1));
- break;
- case 2:
- v.push_back(new Kula(rand()%5+1));
- break;
- }
- }
- }
- void displayCollection(vector <Bryla*> v){
- vector <Bryla*>:: iterator it = v.begin();
- while(it!=v.end()){
- if(dynamic_cast<Szescian*>(*it))
- cout << "Szescian: ";
- else
- cout << "Kula: ";
- cout << (*it)->volume() << endl;
- it++;
- }
- }
- int main(){
- srand(time(NULL));
- vector<Bryla*> kolekcja;
- fillCollection(kolekcja,5);
- displayCollection(kolekcja);
- cout <<"Srednia objetosc: " << meanVolume(kolekcja) << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement