/*This
code was written by A. El-Gadi of Tripoli University for educational
purposes. The code illustrates inheritance and polymorphism in C++. It uses a necklace with several types of beads as an example. For any questions
use the comment section below.*/
#include <iostream>
#include <cmath>
#include <stdlib.h>
using namespace std;
class Bead{
protected:
const double density;
public:
virtual double weight()=0;
virtual void show(){cout<<"-B";}
Bead(double D):density(D){};
virtual ~Bead(){};
};
class SBead:public Bead{
private:
double r;//radius
public:
double weight(){return (4/3*3.14159*r*r*r*density);}
void show(){cout<<"-S";}
void setR(double R){r=R;}
SBead(double R,double D):r(R),Bead(D){};
};
class CBead:public Bead{
private:
double s;//side length
public:
double weight(){return s*s;}
void show(){cout<<"-C";}
void setS(double S){s=S;};
CBead(double S,double D):s(S),Bead(D){};
};
class CyBead:public Bead{
private:
double r;//radius
double h;//height
public:
double weight(){return r*r*h*3.14159;}
void show(){cout<<"-Z";}
void setRH(double R, double H){r=R;h=H;};
CyBead(double R,double H, double D):r(R),h(H),Bead(D){};
};
int main(){
Bead *bds[25];Bead *b;
for(int i=0;i<25;i++){
switch (rand()%3){
case 0: bds[i]=new SBead(10,1.5); break;
case 1: bds[i]=new CBead(10,1.5); break;
case 2: bds[i]=new CyBead(10,5,1.5);}
}
for(int i=0;i<25;i++){bds[i]->show();}
return 0;
}
#include <cmath>
#include <stdlib.h>
using namespace std;
class Bead{
protected:
const double density;
public:
virtual double weight()=0;
virtual void show(){cout<<"-B";}
Bead(double D):density(D){};
virtual ~Bead(){};
};
class SBead:public Bead{
private:
double r;//radius
public:
double weight(){return (4/3*3.14159*r*r*r*density);}
void show(){cout<<"-S";}
void setR(double R){r=R;}
SBead(double R,double D):r(R),Bead(D){};
};
class CBead:public Bead{
private:
double s;//side length
public:
double weight(){return s*s;}
void show(){cout<<"-C";}
void setS(double S){s=S;};
CBead(double S,double D):s(S),Bead(D){};
};
class CyBead:public Bead{
private:
double r;//radius
double h;//height
public:
double weight(){return r*r*h*3.14159;}
void show(){cout<<"-Z";}
void setRH(double R, double H){r=R;h=H;};
CyBead(double R,double H, double D):r(R),h(H),Bead(D){};
};
int main(){
Bead *bds[25];Bead *b;
for(int i=0;i<25;i++){
switch (rand()%3){
case 0: bds[i]=new SBead(10,1.5); break;
case 1: bds[i]=new CBead(10,1.5); break;
case 2: bds[i]=new CyBead(10,5,1.5);}
}
for(int i=0;i<25;i++){bds[i]->show();}
return 0;
}
No comments:
Post a Comment