C++多态
1.1多态性(polymorphism)是面向对象程序设计的一个重要特征。
1.2从系统实现的角度看,多态性分两类:静态多态性与动态多态性。
静态多态性是通过函数重载(运算符重载也是函数重载)来实现的。它又称为编译时多态。
动态多样性是在程序运行过程中才动态确定操作所针对的对象。它又称为运行时多态,动态多态性是通过虚函数来实现的。
1.3一段代码:
#include <iostream>
using namespace std;
class Point
{
public:
Point(float a=0,float b=0);
void setPoint(float a,float b);
float getX() const {return x;}
float getY() const {return y;}
friend ostream& operator << (ostream& output,Point& p);
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;
}
ostream& operator << (ostream& output,Point& p)
{
output << "[" << p.getX() << "," << p.getY() << "]" << endl;
return output;
}
class Circle:public Point
{
public:
Circle(float a,float b,float r):Point(a,b),radius(r){}
void setRadius(float r);
float getRadius() const {return radius;}
float area() const;
friend ostream& operator << (ostream& output,Circle &c);
protected:
float radius;
};
void Circle::setRadius(float r)
{
radius=r;
}
float Circle::area() const
{
return 3.14159*radius*radius;
}
ostream& operator << (ostream& output,Circle &c)
{
output << "Center [" << c.x << "," << c.y << "] radius=" << c.radius
<< " area=" << c.area() << endl;
return output;
}
class Cylinder:public Circle
{
public:
Cylinder(float a,float b,float r,float h):Circle(a,b,r),height(h){}
void setHeight(float h){height=h;}
float getHeight() const{return height;}
float area() const;
float volume() const;
friend ostream& operator << (ostream& output,Cylinder& cy);
protected:
float height;
};
float Cylinder::area() const
{
return 2*Circle::area()+2*3.14159*radius*height;
}
float Cylinder::volume() const
{
return Circle::area()*height;
}
ostream& operator << (ostream& output,Cylinder& cy)
{
output << "Center [" << cy.getX() << "," << cy.getY() << "] r="
<< cy.radius << "\narea=" << cy.area() << " volume=" << cy.volume()
<< endl;
return output;
}
int main()
{
Cylinder cy(1,2,3,4);
cout <<"Cylinder\n" << "Center [" << cy.getX() << "," << cy.getY() << "] r="
<< cy.getRadius() << "\narea=" << cy.area() << " volume=" << cy.volume()
<< endl;
cy.setHeight(1);
cy.setPoint(2,3);
cy.setRadius(4);
cout << "Cylinder\n" << cy << endl;
Point &p=cy;
cout << "Point\n" << p;
Circle &c=cy;
cout << "Circle\n" << c;
return 0;
}
1.4在本例中存在静态多态性,这是由运算符重载引起的,可以看到,在编译时编译系统即可以判定应调用哪个运算符函数。