派生类中对基类成员的重定义
重定义:在派生类中可定义与基类成员同名的成员,此时在派生类中 有两个同名的成员。同名成员:同名数据成员:同名同名成员函数:必须与基类成员函数 具有相同原型说明 (返回类型、函数名、参数类型与个数),否则为函数重载而非重定义。在一个类中不能定义两个函数原型说明完全相同的成员函数,重定 义成员函数只能出现在具有继承关系的类中(派生类)。同名成员函数的访问:在派生类中基类的同名成员被屏蔽。若在派生类中访问基类的被屏蔽成员,则必须使用作用域运算符::,即在成员前增加 类名 ::以明确指定其所属的类。(跟局部变量的屏蔽类似)
基类名 ::基类同名数据成员
基类名 :: 基类同名成员函数(实参列表)
同名成员函数例: Cylinder类中也定义了名为 getArea的成员函数,用以计算圆柱体的表面积。
- // circle.h文件
- class Circle
- {
- protected:
- double radius;
- public:
- Circle();
- Circle(double);
- double getArea();
- double getPerimeter();
- double getRadius();
- void setRadius(double);
- };
- // cylinder.h文件
- #include "circle.h"
- class Cylinder: public Circle
- {
- protected:
- double height;
- public:
- Cylinder();
- Cylinder(double h);
- Cylinder(double r,double h);
- double getArea();
- double getVolume();
- double getHeight();
- void setHeight (double h);
- };
- double Cylinder::getArea()
- {
- return 2 * Circle::getArea() + getPerimeter() * height;
- }
- double Cylinder::getVolume()
- {
- return Circle::getArea() * height;
- }
- void main()
- {
- Cylinder c(1.5,10);
- cout<< c.getArea() <<endl; // 输出圆柱体的表面积
- cout<< c.Circle::getArea() <<endl;//输出圆柱体的圆面积
- }