C++语言程序设计 清华大学郑莉 公有继永(public) 类 成 基类的oublic和protected成员的访问 员 属性在派生类中保持不变,但基类的 的 private成员不可直接访问。 访·派生类中的成员函数可以直接访问基类 问 中的oublic和protected,成员,但不能 控 直接访问基类的private成员。 制·通过派生类的对象只能访问基类的 public,成员
C++语言程序设计 清华大学 郑莉 11 公有继承(public) ⚫ 基类的public和protected成员的访问 属性在派生类中保持不变,但基类的 private成员不可直接访问。 ⚫ 派生类中的成员函数可以直接访问基类 中的public和protected成员,但不能 直接访问基类的private成员。 ⚫ 通过派生类的对象只能访问基类的 public成员。 类 成 员 的 访 问 控 制
C++语言程序设计 清华大学郑莉 例71公有继永举例 类 成 class Point{/基类Point类的定义 public: /公有函数成员 员 void initPoint(float x 0,float y 的 0){this->x=x;this->y=y; 访 void move(float offX,float offY) x +offX;y +offy; 问 float getx()const return x; 控 float gety()const return y; 制 private: /私有数据成员 float x,y; 12
C++语言程序设计 清华大学 郑莉 12 例7-1 公有继承举例 class Point { //基类Point类的定义 public: //公有函数成员 void initPoint(float x = 0, float y = 0) { this->x = x; this->y = y;} void move(float offX, float offY) { x += offX; y += offY; } float getX() const { return x; } float getY() const { return y; } private: //私有数据成员 float x, y; }; 类 成 员 的 访 问 控 制
class Rectangle:public Point //派生类定义部 分 public: //新增公有函数成员 void initRectangle(float x,float y,float w, float h) initPoint(x,y);/调用基类公有成员函数 this->ww; this->hh; float getH(const return h; float getw(const return w; private: //新增私有数据成员 float w,h;
class Rectangle: public Point { //派生类定义部 分 public: //新增公有函数成员 void initRectangle(float x, float y, float w, float h) { initPoint(x, y); //调用基类公有成员函数 this->w = w; this->h = h; } float getH() const { return h; } float getW() const { return w; } private: //新增私有数据成员 float w, h; }; 13
#include <iostream> #include〈cmath> using namespace std; int mainO) Rectangle rect; //定义Rectanglez类的对象 //设置矩形的数据 rect.initRectangle(2,3,20,10); rect.move(3,2);//移动矩形位置 cout <"The data of rect(x,y,w,h):"< endl //输出矩形的特征参数 cout <rect.getx()<<" <rect.getY()<<" rect.getw <rect.getH()<<endl; return 0; 14
#include <iostream> #include <cmath> using namespace std; int main() { Rectangle rect; //定义Rectangle类的对象 //设置矩形的数据 rect.initRectangle(2, 3, 20, 10); rect.move(3,2); //移动矩形位置 cout << "The data of rect(x,y,w,h): " << endl; //输出矩形的特征参数 cout << rect.getX() <<", " << rect.getY() << ", " << rect.getW() << ", " << rect.getH() << endl; return 0; } 14
C++语言程序设计 清华大学郑莉 私有继永(private) 类 成 基类的public和orotected成员都以 员 private身份出现在派生类中,但基类 的 的private成员不可直接访问。 访 ● 派生类中的成员函数可以直接访问基 问 类中的oublic和orotected成员,但 不能直接访问基类的private成员。 控 制 ·通过派生类的对象不能直接访问基类 中的任何成员。 15
C++语言程序设计 清华大学 郑莉 15 私有继承(private) ⚫ 基类的public和protected成员都以 private身份出现在派生类中,但基类 的private成员不可直接访问。 ⚫ 派生类中的成员函数可以直接访问基 类中的public和protected成员,但 不能直接访问基类的private成员。 ⚫ 通过派生类的对象不能直接访问基类 中的任何成员。 类 成 员 的 访 问 控 制