/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称: 《抽象基类的应用》
* 作 者: 刘江波
* 完成日期: 2012 年 5 月 15 日
* 版 本 号: v.05153
* 对任务及求解方法的描述部分
* 问题描述:
设计一个抽象类CSolid,含有两个求表面积及体积的纯虚函数。设计个派生类CCube、CBall、CCylinder,分别表示正方体、球体及圆柱体。在main()函数中,定义基类的指针p(CSolid *p;),利用p指针,输出正方体、球体及圆柱体对象的表面积及体积。
* 程序头部的注释结束
*/
#include<iostream>
using namespace std;
const double PI = 3.14159;
class CSolid
{
public:
virtual double area() const =0;
virtual double volume() const =0;
};
class CCube: public CSolid
{
public:
CCube(double length);
virtual double area() const;
virtual double volume() const;
void show_area();
void show_volume();
protected:
double length;
};
class CBall: public CSolid
{
public:
CBall(double radius);
virtual double area() const;
virtual double volume() const;
protected:
double radius;
};
class CCylinder: public CSolid
{
public:
CCylinder(double height, double radius);
virtual double area() const;
virtual double volume() const;
void show_area();
void show_volume();
protected:
double height;
double radius;
};
CCube::CCube(double length)
{
this->length = length;
}
double CCube::area() const
{
return (this->length * this->length * 6);
}
double CCube::volume() const
{
return (this->length * this->length * this->length);
}
CBall::CBall(double radius)
{
this->radius = radius;
}
double CBall::area() const
{
return (4 * PI * this->radius * this->radius);
}
double CBall::volume() const
{
return (PI * this->radius * this->radius * this->radius * 3 / 4);
}
CCylinder::CCylinder(double height, double radius)
{
this->height = height;
this->radius = radius;
}
double CCylinder::area() const
{
return (2 * (PI * this->radius * this->radius) + this->height * (2 * PI * this->radius));
}
double CCylinder::volume() const
{
return (PI * this->radius * this->radius * this->height);
}
int main()
{
CSolid *p;
CCube ccube(5);
CBall cball(4);
CCylinder ccylinder(10, 2);
p = &ccube;
cout << "正方体的表面积是:" << p->area() << endl;
cout << "正方体的体积是:" << p->volume() << endl;
p = &cball;
cout << "球体的表面积是:" << p->area() << endl;
cout << "球体的体积是:" << p->volume() << endl;
p = &ccylinder;
cout << "圆柱体的表面积是:" << p->area() << endl;
cout << "圆柱体的体积是:" << p->volume() << endl;
system("pause");
return 0;
}
抽象基类太实用了