#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.get( <rect.getH()<<endl; return 0; 日 16
#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; } 16
C++语言程序设计 私有继承(private) 类 成 ● 基类的public和orotected,成员都以 员 private身份出现在派生类中,但基类 的 的private)成员不可直接访问。 访 ●派生类中的成员函数可以直接访问基 问 类中的oublic和protected成员,但 不能直接访问基类的private成员。 控 制 ·通过派生类的对象不能直接访问基类 中的任何成员
C++语言程序设计 17 私有继承(private) 基类的public和protected成员都以 private身份出现在派生类中,但基类 的private成员不可直接访问。 派生类中的成员函数可以直接访问基 类中的public和protected成员,但 不能直接访问基类的private成员。 通过派生类的对象不能直接访问基类 中的任何成员。 类成员的访问控制
C+语言程序设计 例7-2私有继永举例 类 class Rectangle:private Point{/派生类定义部分 public://新增公有函数成员 成 yoid initRectangle(float x,float y,float w, float h) 员 initPoint(x,y);/调用基类公有成员函数 this->w=w; 的 this->hh; 访 void move(float offX,float offY){ Point:move (offX,offY); 问 float getx const 控 return Point:getx(); float getY() const return Point:getY(); float getH() const return h; 制 float getw(const return w: private: /新增私有数据成员 float w,h;
C++语言程序设计 18 例7-2 私有继承举例 class Rectangle: private Point { //派生类定义部分 public://新增公有函数成员 void initRectangle(float x, float y, float w, float h) { initPoint(x, y); //调用基类公有成员函数 this->w = w; this->h = h; } void move(float offX, float offY) { Point::move(offX, offY); } float getX() const { return Point::getX(); } float getY() const { return Point::getY(); } float getH() const { return h; } float getW() const { return w; } private: //新增私有数据成员 float w, h; }; 类成员的访问控制
#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.getX0<”,”/输出矩形的特征参数 <rect.getY()<<"," <rect.getw()<<"," <rect.getH()<endl; return 0; } 日 19
#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; } 19
C++语言程序设计 保护继承(protected) 类 成 ● 基类的public和orotected,成员都以 员 protected.身份出现在派生类中,但 的 基类的private,成员不可直接访问。 访 ●派生类中的成员函数可以直接访问基 问 类中的oublic和protected成员,但 不能直接访问基类的private,成员。 控 制 ·通过派生类的对象不能直接访问基类 中的任何成员
C++语言程序设计 20 保护继承(protected) 基类的public和protected成员都以 protected身份出现在派生类中,但 基类的private成员不可直接访问。 派生类中的成员函数可以直接访问基 类中的public和protected成员,但 不能直接访问基类的private成员。 通过派生类的对象不能直接访问基类 中的任何成员 类成员的访问控制