10.4抽象クラス
1889 ワード
/*
* Copyright (c) 2014,
* All rights reserved.
* :
* :2014 5 28
* :v1.0
* :
* : CSolid, 。
CCube、CBall、CCylinder, 、 。 main() ,
CSolid *p;(p , )。
p , 、 。
* :
* :
* :
*/
#include <iostream>
#include <iomanip>
#define pi 3.14
using namespace std;
class CSolid
{
public:
virtual float superficial() =0;
virtual float volume() =0;
};
class CCube:public CSolid
{
public:
CCube(float a1):a(a1){}
virtual float superficial()
{
return 8*a*a;
}
virtual float volume()
{
return a*a*a;
}
private:
float a;
};
class CBall:public CSolid
{
public:
CBall(float r1):r(r1){}
virtual float superficial()
{
return 4*pi*r*r;
}
virtual float volume()
{
return (3/4)*pi*r*r*r;
}
private:
float r;
};
class cylinder:public CSolid
{
public:
cylinder(float h1,float r1):h(h1),r(r1){}
virtual float superficial()
{
return (2*pi*r*h+2*2*pi*r);
}
virtual float volume()
{
return pi*r*r*h;
}
private:
float h,r;
};
int main()
{
cout<<fixed<<setprecision(2);
cylinder cylinder(2.1,5.1);
CCube CCube(2);
CBall CBall(3);
CSolid *pt;
pt=&CCube;
cout<<" :"<<pt->superficial()<<endl;
cout<<" :"<<pt->volume()<<endl;
pt=&CBall;
cout<<" :"<<pt->superficial()<<endl;
cout<<" :"<<pt->volume()<<endl;
pt=&cylinder;
cout<<" :"<<pt->superficial()<<endl;
cout<<" :"<<pt->volume()<<endl;
return 0;
}