C++学习心得(3)多态性与虚函数
——from 谭浩强.C++面向对象程序设计(第一版)
2014/10/13
6.1 多态性的概念
在C++中,多态性是指具有不同功能的函数可以用同一个函数名,这样就可以用一个函数名调用不同内容的函数。
面向对象的描述:向不同的对象发送同一个消息,不同的对象在接收时会产生不同的行为。即每个对象可以用自己的方式去响应共同的消息。
静态多态性:编译时的多态性,函数重载、运算符重载
动态多态性:运行时的多态性,虚函数
6.2 一个典型的例子
// (1)声明基类Point类
#include <iostream>
using namespace std;
class Point
{
public:
Point(float x = 0, float y = 0); // 声明有默认参数的构造函数
void setPoint(float, float); // 设置坐标值
float getX() const // 取得x坐标
{
return x;
}
float getY() const // 取得y坐标
{
return y;
}
friend ostream & operator <<(ostream &, const Point &); //重载运算符<< ,使之能输出Point
protected:
float x, y;
};
// 定义Point的构造函数
Point::Point(floata, float b)
{
x = a;
y = b;
}
void Point::setPoint(float a, float b)
{
x = a;
y = b;
}
ostream & operator << (ostream &output, const Point &p)
{
output << "[" << p.x<< "," << p.y << "]" << endl;
return output;
}
// int main()
// {
// <span style="white-space:pre"> </span>Point p(3.4, 6.5);
// <span style="white-space:pre"> </span>cout << "x = " <<p.getX() << "," << "y = " << p.getY()<< endl;
// <span style="white-space:pre"> </span>p.setPoint(8.5, 6.8);
// <span style="white-space:pre"> </span>cout << "p(new):" << p<< endl;
// <span style="white-space:pre"> </span>return 0;
// }
class Circle: public Point
{
public:
Circle(float x = 0, float y = 0, float r= 0); // 声明构造函数
void setRadius(float); //设置半径值
float getRadius() const; // 读取半径值
float area() const; //计算圆面积
friend ostream & operator <<(ostream &, const Circle &); //重载运算符 <<
protected:
float radius;
};
// 完善
Circle::Circle(floata, float b, float r):Point(a, b), radius(r) {}
void Circle::setRadius(float r)
{
radius = r;
}
float Circle::getRadius() const
{
return radius;
}
float Circle::area() const
{
return 3.14159265389*radius*radius;
}
ostream & operator << (ostream &output, const Circle &c)
{
output << "Center = "<< "[" << c.x << "," << c.y<< "]" << "," << "r = "<< c.radius << "," << "area = " <<c.area() << endl;
return output;
}
// int main()
// {
// <span style="white-space:pre"> </span>Circle c(3.5, 6.4, 5.2);
// <span style="white-space:pre"> </span>cout << "original circle: \n x =" << c.getX() << "," << "y = "<< c.getY() << "," << "r = " <<c.getRadius() << ",area = " << c.area() << endl;
// <span style="white-space:pre"> </span>c.setRadius(7.5);
// <span style="white-space:pre"> </span>c.setPoint(5,5);
// <span style="white-space:pre"> </span>cout << "new circle:\n"<< c;
// <span style="white-space:pre"> </span>Point &pRef = c;
// <span style="white-space:pre"> </span>cout << "pRef:" << pRef;
// <span style="white-space:pre"> </span>return 0;
// }
class Cylinder: public Circle
{
public:
Cylinder(float x = 0, float y = 0, floatr = 0, float h = 0);
void setHeight(float);
float getHeight() const;
float area() const;
float volume() const;