虚函数和纯虚函数
来源:互联网 发布: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();}
- 虚基类和纯虚函数
- 继承和纯虚函数
- 纯虚函数和纯虚析构
- 虚函数和纯虚函数
- 虚函数和纯虚函数
- 虚函数和纯虚函数1
- 虚函数和纯虚函数区别
- 虚函数和纯虚函数区别
- 虚函数和纯虚函数
- 虚函数和纯虚函数
- 虚函数和纯虚函数
- 虚函数和纯虚函数区别
- 多态性和虚函数、纯虚函数
- 虚函数和纯虚函数
- 虚函数 和 纯虚函数
- 虚函数和纯虚函数
- 虚函数和纯虚函数
- 虚函数和纯虚函数
- POJ 1106 Transmitters
- struts地址栏中重写Url
- asp.net 应用程序对象 HttpContext 和 HttpApplication (1)
- 软件项目管理系统-采购商品管理-采购订单一览
- iPhone手机和Android手机的对比
- 虚函数和纯虚函数
- 文件大小和占用空间的区别
- eclipse.ini/myeclipse.ini中配置参数 -Xms,-Xmx,-PerSize //优化eclipse
- 用WPF做一个像QQ登陆界面一样的窗体
- WinForm程序中两份mdf文件问题的解决(转载 )
- Android解析JSON方式(二) 客户端解析SON数据
- 如果你已经过了20还不到25岁
- vertical-align 模型图
- 解决.windows media player打不开MMS协议流媒体的问题