关于C++中的纯虚函数,使用方法个人理解就像是java中的interface一样,
使用规则为
1.在基类中定义虚函数。
2.在派生类中通过函数覆盖来定义同名的函数。
3.定义基类的指针并调用该函数。
#include "stdafx.h"
#include<iostream>
using namespace std;
const double PI = 3.1415926;
class Container
{
protected:
double radius;
public:
Container(double r);
virtual double surface_area() = 0;
virtual double volume() = 0;
};
Container::Container(double r)
{
radius = r;
}
class Sphere:public Container
{
public:
Sphere(double);
double surface_area();
double volume();
};
Sphere::Sphere(double r):Container(r)
{
radius = r;
}
double Sphere::surface_area()
{
return 4 * PI*radius*radius;
}
double Sphere::volume()
{
return (4 / 3)*PI*radius*radius*radius;
}
class Cylinder :public Container
{
public:
Cylinder(double,double);
double surface_area();
double volume();
private:
double height;
};
Cylinder::Cylinder(double r,double h) :Container(r)
{
height = h;
radius = r;
}
double Cylinder::surface_area()
{
return PI*radius*radius * 2 + 2 * PI*radius*height;
}
double Cylinder::volume()
{
return PI*radius*radius*height;
}
class Cube :public Container
{
public:
Cube(double);
double surface_area();
double volume();
};
Cube::Cube(double r) :Container(r)
{
radius = r;
}
double Cube::surface_area()
{
return 6 * radius;
}
double Cube::volume()
{
return radius*radius*radius;
}
int main()
{
Container *s = new Sphere(5.0);
Container *c = new Cylinder(5.0,6.0);
Container *cube = new Cube(6.0);
cout << "计算边长为6.0的正方体、半径为5.0的球体,以及半径为5.0和高为6.0的圆柱体的表面积和体积." << endl;
cout << "球体表面积为: " << s->surface_area()<<endl;
cout << "球体体积为: " << s->volume()<<endl;
cout << "圆柱体表面积为: " << c->surface_area() << endl;
cout << "圆柱体体积为: " << c->volume() << endl;
cout << "正方体表面积为: " << cube->surface_area() << endl;
cout << "正方体体积为: " << cube->volume() << endl;
system("pause");
return 0;
}