C++练习(六)多态性与虚函数

定义基类Base,其数据成员为高h,定义成员函数disp()为虚函数。然后,再由基类派生出长方体类Cuboid与圆柱体类Cylinder。
并在两个派生类中定义成员函数disp()为虚函数。在主函数中,用基类Base定义指针变量pc,然后用指针pc动态调用基类与

派生类中的虚函数disp(),显示长方体与圆柱体的体积。

#include
using namespace std;

class Base{
protected:
	double h;
public:
	Base(double height)
	{h=height;}
	virtual double disp()=0;
};

class Cuboid:public Base
{
protected:
	double l;double w;
public:
	Cuboid(double lon,double width,double height):Base(height)
	{
		l=lon;
		w=width;
	}
		double disp()
	{return l*w*h;}
};

class Cylinder:public Base
{
protected:
	double pi;double r;
public:
	Cylinder(double p,double radiums,double height):Base(height)
	{
		pi=p;
		r=radiums;
	}
	double disp()
	{
		return pi*r*r*h;
	}
};

int main()
{
	Base *pc;
	Cuboid cu(10.0,8.0,8.0);
	Cylinder cy(3.14,4.0,5.0);
	pc=&cu;
	cout<<"长方体的体积"<disp()<disp()<
C++练习(六)多态性与虚函数_第1张图片

你可能感兴趣的:(C++练习)