在 privates和 protected中声明的数据成 员和成员函数构成类的私有部分,只能由 该类的对象和成员函数,以及声明为友元 ( friend)的函数或类的对象才能访问它们。 在 protected中声明的数据成员和成员函 数,还允许该类的派生类访问它们; 在 private域中声明的数据成员和成员函数, 则不允许该类的派生类访问它们。 下面给出一个 point类的声明。 Point类中 点的表示由两个整数变量x,y组成。类的 用户不能直接访问它们。 16
16 ◼ 在private域和protected域中声明的数据成 员和成员函数构成类的私有部分,只能由 该类的对象和成员函数,以及声明为友元 (friend)的函数或类的对象才能访问它们。 ◼ 在protected域中声明的数据成员和成员函 数,还允许该类的派生类访问它们; ◼ 在private域中声明的数据成员和成员函数, 则不允许该类的派生类访问它们。 ◼ 下面给出一个 point 类的声明。Point 类中 点的表示由两个整数变量x, y 组成。类的 用户不能直接访问它们
#ifndef Point h #define point h //n the header file point. h class point i /类定义 p rivate /私有域 Int x, 数据成员:点坐标 int public: ∥/共有域 Point(int,int);/构造函数 Pont( point e&);/复制构造函数 Point (; ∥析构函数 int get xo; ∥取x坐标 int get y ( 取y坐标
17 #ifndef POINT_H #define POINT_H //In the header file point.h class Point { //类定义 private: //私有域 int x; //数据成员:点坐标 int y; public: //共有域 Point ( int, int ); //构造函数 Point ( Point & ); //复制构造函数 ~Point ( ); //析构函数 int get_x ( ); //取x坐标 int get_y ( ); //取y坐标
Point operator+( point);∥点加点 Point operator(int) ∥/点除整数 Point operator * int ) ∥点乘整数 int operator >( Point) ∥/点比较 int operator < Point ) ∥/点比较 int operator=( Point&);∥点比较 friend istream& operator >> ( istream&, Point);∥入友元函数 friend ostream& operator < ( ostream&,pomt&;/输出友元函数 #endif
18 Point operator + ( point ); //点加点 Point operator / ( int ); //点除整数 Point operator * ( int ); //点乘整数 int operator > ( Point ); //点比较 int operator < ( Point ); //点比较 int operator == ( Point& ); //点比较 friend istream& operator >> ( istream&, Point& ); //输入友元函数 friend ostream& operator << ( ostream&, Point& ); //输出友元函数 }; #endif
为了存取一个点的x,y分量,类提供了两个 函数getx,gety。这样可用 private域来保 护数据的表示,防止类的用户直接使用数 据的内部表示来编写代码,通过使用存取 函数来操作数据来维持类的抽象性 private是声明默认的存取级别。 系统开发时把类的声明放在头文件中,成 员函数的实现放在源程序文件中。在源程 序文件中函数的实现通过作用域设定命令 :”而被归属到某一个类
19 ◼ 为了存取一个点的x, y分量, 类提供了两个 函数get_x, get_y。这样可用private域来保 护数据的表示, 防止类的用户直接使用数 据的内部表示来编写代码,通过使用存取 函数来操作数据来维持类的抽象性。 ◼ private是声明默认的存取级别。 ◼ 系统开发时, 把类的声明放在头文件中, 成 员函数的实现放在源程序文件中。在源程 序文件中函数的实现通过作用域设定命令 “::”而被归属到某一个类
例,对于Poin类的输出友元函数的实现可以 在源程序文件中给出,形为: ostream operator <<(ostream& strm Point p return strm <<"(<<p get x( <","<< p get y(<"); 这个函数把点p的值以“x,y"的格式送到srm 指明的输出流中去。 20
20 例,对于Point类的输出友元函数的实现可以 在源程序文件中给出,形为: ostream & operator << (ostream& strm, Point p) { return strm << "(" << p.get_x ( ) << "," << p.get_y () << ")"; } 这个函数把点p的值以“x, y”的格式送到strm 指明的输出流中去