虚函数和纯虚函数

来源:互联网 发布:2016淘宝达人怎么赚钱 编辑:程序博客网 时间:2024/04/28 15:34
#include<iostream>using namespace std;class CPoint{public:double x,y;CPoint(double a,double b);virtual double area();//此处需要用虚函数};CPoint::CPoint(double a,double b){x=a;y=b;}double CPoint:: area(){return 110;}class CRectangle:public CPoint{double z;public:CRectangle(double a,double b):CPoint(a,b){z=0.0;}virtual double  area();//此处需要用虚函数};double CRectangle::area(){z=x*y;return z;}void main(){CPoint p1(3.8,6.7);CRectangle r1(5.6,9.9);CPoint *q;q=&r1;cout << q->area() << endl;cout << "-----------" << endl;q=&p1;cout << q->area() << endl;cout << "-----------" << endl;CPoint &m=r1;cout <<m.area() << endl;cout << r1.area() << endl;}


为改为虚函数时候:

声明的指针p为基类CPoint的对象指针,因此在编译时候,编译系统为语句 cout << q->area() << endl;中的q->area()绑定CPoint::area() 函数。运行时候虽然基类对象指针p指向了派生类对象r1,但是由于系统已经静态绑定了基类的成员函数area(),因此该语句并没有调用派生类的成员函数。

另外,在程序中又声明了一个基类对象的引用m,并将其初始化为派生类对象r1,。由于基类中的成员函数area()是一般的成员函数,编译系统为语句cout <<m.arae() <<endl;中的m.area()绑定了CPoint::area()函数,因此该语句调用基类中的成员函数area()。

运行是多态性必须由虚函数来完成。


#include<iostream>using namespace std;class CFigure{protected:float x,y;public:void setdim(float i,float j=0){x=i;y=j;}virtual void area()=0;};class CTriangle:public CFigure{public:void area(){cout << "三角形的底边和高分别是:" << x << ","<< y << endl;cout << "三角形的面积是:" << x*0.5*y << endl;}};class CSquare:public CFigure{public:void area(){cout <<"矩形的长和宽分别是:"<< x << "," << y <<endl;cout << "矩形的面积是:"  << x*y << endl;}};class CCircle:public CFigure{public:void area(){cout <<"圆的半径是:" << x <<endl;cout << "圆的面积是:" <<3.14*x*x << endl;}};void main(){CFigure *p;CTriangle t;CSquare s;CCircle c;p=&t;p->setdim(10.0,5.0);p->area();p=&s;p->setdim(10.0,5.0);p->area();p=&c;p->setdim(9.0);p->area();}


由基类CFigure派生出了CTriangle类、CSquare类和CCircle类。基类CFigure的成员函数area()是纯虚函数。他的实现分别在派生类中定义。在main()函数中,通过基类指针指向不同的派生类对象时,就调用派生类中area()函数的不同实现版本,从而实现了运行时的多态性。

原创粉丝点击