多态性 学习笔记1

来源:互联网 发布:js设置文本框提示文字 编辑:程序博客网 时间:2024/05/04 23:34

函数和运算符的重载

一般函数的重载

定义两个类,CPoint和CRectangle。CRectangle是从基类CPoint公有派生的。在派生类中重新定义了成员函数area()。如下:
#include<iostream>class CPoint{public:double x,y;CPoint(double a,double b);double area();};CPoint::CPoint(double a,double b){x=a;y=b;}double CPoint::area(){return 0.0;}class CRectangle:public CPoint{double z;public:CRectangle(double a,double b):CPoint(a,b){z=0.0;}double area();};double CRectangle::area(){z=x*y;return z;}using namespace std;void main() {CPoint p1(3.8,6.7);CRectangle r1(5.6,9.9);cout << p1.area() << endl;cout << r1.area() << endl;cout << r1.CPoint::area() << endl;cout << r1.CRectangle::area() << endl;}



CPoint p1(3.8,6.7);
CRectangle r1(5.6,9.9);
cout << p1.area() << endl; //调用基类中的area()函数
cout << r1.area() << endl;//调用派生类中的area()函数,求矩形面积
cout << r1.CPoint::area();//调用基类中的area()函数
cout << r1.CRectangle::area() << endl;//调用派生类中的area()函数
原创粉丝点击