c++知识点----定义抽象基类(纯虚函数)

题目:

写一个函数,定义抽象基类Container,由它派生出3个派生类:Sphere(球体)、Cylinder(圆柱体)、Cube(正方体)。用虚函数分别计算几种图形的表面积和体积


c++知识点----定义抽象基类(纯虚函数)_第1张图片用到的文件


main.cpp

#include 
using namespace std;
#define PI 3.14159
#include "class.h"
int main()
{
	Sphere s1(3);
	cout << "面积:" << s1.area() << endl;
	cout << "体积:" << s1.volume() << endl;
	Cylinder c1(3,3);
	cout << "面积:" << c1.area()<< endl;
	cout << "体积:" << c1.volume() << endl;
	Cube cu1(3);
	cout << "面积:" << cu1.area() << endl;
	cout << "体积:" << cu1.volume() << endl;
	system("pause");
	return 0;
}

class.h

#pragma once
class Container
{
public:
	Container(double r,double h);//初始化私有变量
	Container(double );
	virtual double area() = 0;//虚函数 -- 计算面积
	virtual double volume() = 0;//虚函数 -- 计算体积
protected:
	double R;
	double highth;

};
Container::Container(double r, double h):R(r),highth(h)
{	}
inline Container::Container(double r):R(r),highth(r)
{	}

//------------------------------------------------
class Sphere: public Container //球体
{
public:
	Sphere(double r);
	virtual double area();//返回球体的面积
	virtual double volume();//返回球体的体积
private:

};
Sphere::Sphere(double r):Container(r)
{	}
inline double Sphere::area()
{
	return 4*PI*R;
}
inline double Sphere::volume()
{
	return (4.0/3)*PI*R*R*R;
}
//-------------------------------------------------
class Cylinder:public Container   //圆柱体
{
public:
	Cylinder(double r,double h);//初始化
	virtual double area();//计算圆柱体的面积
	virtual double volume();//计算圆柱体的体积
private:

};

Cylinder::Cylinder(double r,double h):Container(r,h)
{	}
inline double Cylinder::area()
{
	return 2*PI*R*R + 2*PI*R*highth;
}
inline double Cylinder::volume()
{
	return PI*R*R*highth;
}
//-------------------------------------------------
class Cube:public Container //正方体
{
public:
	Cube(double h);
	virtual double area();//计算正方体的面积
	virtual double volume();//计算正方体的体积
private:

};
Cube::Cube(double h):Container(h)
{	}
inline double Cube::area()
{
	return 6*highth*highth;
}
inline double Cube::volume()
{
	return highth*highth*highth;
}


运行结果:

c++知识点----定义抽象基类(纯虚函数)_第2张图片分别是球体、圆柱体、正方体


使用软件:vs2015

你可能感兴趣的:(c++综合运用)