#include<iostream>
using namespace std;
const float PI=3.14;
//define abstract class
class Shape
{
public:
virtual float area() {return 0;}//抽象基类中的三个虚函数,其中一个是纯虚函数。
virtual float volume() {return 0;}
virtual void shapeName() =0;
};
//定义Point类
class Point:public Shape
{
public:
Point(float=0,float=0);
void setPoint(float a,float b);
float getX()const {return x;}
float getY()const {return y;}
virtual void shapeName() {cout<<"Point:";}
friend ostream& operator<< (ostream& o,const Point& p){
o<<"["<<p.x<<" , "<<p.y<<"]";
return o;
}
protected:
float x,y;
};
Point::Point(float a,float b):x(a),y(b){
}
void Point::setPoint(float a,float b){
x=a,y=b;
}
//定义Globe类
class Globe:public Point
{
public:
float getR()const {return r;}
Globe(float=0,float=0,float=0);
//多态的前提是多态中的虚函数和抽象基类中的虚函数的生命完全一样(包括后面的const )
virtual float area() ; //抽象基类中的三个虚函数,其中一个是纯虚函数。
virtual float volume() ;
virtual void shapeName() {cout<<"Globe:";}
//virtual float area();
//virtual float volume();
//virtual void shapeName();
friend ostream& operator<< (ostream& ,Globe&);
protected:
float r;
};
Globe::Globe(float a,float b,float c):Point(a,b),r(c){
}
float Globe::area()
{
return (4*PI*r*r);
}
float Globe::volume()
{
return (1.33*PI*r*r*r);
}
ostream& operator<< (ostream& o, Globe& g)
{
o<<"["<<g.x<<" , "<<g.y<<"]"<<", "<<"r="<<g.r<<"\n"
<<"area="<<g.area()<<"\n"
<<"volume="<<g.volume();
return o;
}
int main()
{
Point point(3.2,4.5);
Globe globe(3.3,4.6,5);
point.shapeName();
cout<<point<<endl;
cout<<"------------------------------------------"<<endl;
cout<<"------------------------------------------"<<endl;
globe.shapeName();
cout<<globe<<"\n\n\n"<<endl;
Shape* p;
//将p指向point
p=&point;
p->shapeName();
//cout<<"x="<<p->getX()<<","<<"y="<<p->getY()<<endl; //此处修改为通过point对象访问派生类的新函数
cout<<"x="<<point.getX()<<", "<<"y="<<point.getY()<<endl; //此处妄想通过p指针访问派生类的新函数
cout<<"area="<<point.area()<<"\n" //此处继承下来的函数也改为point对象修改
<<"volume="<<p->volume()<<endl;
cout<<"---------------------------------------------------------"<<endl;
//将p指向globe
p=&globe;
p->shapeName();
//cout<<"x="<<p->getX()<<","<<"y="<<p->getY()<<endl; //此处修改为通过point对象访问派生类的新函数
cout<<"x="<<globe.getX()<<", "<<"y="<<globe.getY()<<", "<<"r="<<globe.getR()<<endl; //此处妄想通过p指针访问派生类的新函数
cout<<"area="<<p->area()<<"\n" //此处继承下来的函数也改为point对象修改
<<"volume="<<p->volume()<<endl;
return 0;
}
其中,Globe是从Point派生来的,Point从抽象基类Shape派生类的。只要派生类中的虚函数声明和抽象基类中的虚函数的声明完全一样,那么无论派生几代,其虚函数都可以帮助类实现多态化。