1、常见的访问修饰符
1)public(共有成员)
修饰成员在任意地方都可以访问。公有成员在程序中类的外部是可访问的。可以不使用任何成员函数来设置和获取公有变量的值。
例如,
#includeusing namespace std;class Line{ public: double length; void setLength( double len ); double getLength( void );};// 成员函数定义double Line::getLength(void){ return length ;}void Line::setLength( double len ){ length = len;}// 程序的主函数int main( ){ Line line; // 设置长度 line.setLength(6.0); cout << "Length of line : " << line.getLength() < 2)private(私有成员)
修饰的成员只能够在类中或者友元函数中可以访问。私有成员变量或函数在类的外部是不可访问的,甚至是不可查看的。只有类和友元函数可以访问私有成员。默认情况下,类的所有成员都是私有的。
width
是一个私有成员。例如,
#includeusing namespace std;class Box{ public: double length; void setWidth( double wid ); double getWidth( void ); private: double width;};// 成员函数定义double Box::getWidth(void){ return width ;}void Box::setWidth( double wid ){ width = wid;}// 程序的主函数int main( ){ Box box; // 不使用成员函数设置长度 box.length = 10.0; // OK: 因为 length 是公有的 cout << "Length of box : " << box.length < 2)protected(保护成员)
修饰的成员可以在类中的函数、子类函数及友元函数中访问。
保护成员变量或函数与私有成员类似,但有一点不同,保护成员在派生类(即子类)中是可访问的。
例如,
#includeusing namespace std;class Box{ protected: double width;};class SmallBox:Box // SmallBox 是派生类{ public: void setSmallWidth( double wid ); double getSmallWidth( void );};// 子类的成员函数double SmallBox::getSmallWidth(void){ return width ;}void SmallBox::setSmallWidth( double wid ){ width = wid;}// 程序的主函数int main( ){ SmallBox box; // 使用成员函数设置宽度 box.setSmallWidth(5.0); cout << "Width of box : "<< box.getSmallWidth() << endl; return 0;} 2、访问修饰符继承
有
public
,protected
,private
三种继承方式,它们相应地改变了基类成员的访问属性。1)public 继承
基类
public
成员,protected
成员,private
成员的访问属性在派生类中分别变成:public
,protected
,private
2)protected 继承
基类
public
成员,protected
成员,private
成员的访问属性在派生类中分别变成:protected
,protected
,private
3)private 继承
基类
public
成员,protected
成员,private
成员的访问属性在派生类中分别变成:private
,private
,private
注意:
private
成员只能被本类成员(类内)和友元访问,不能被派生类访问;
protected
成员可以被派生类访问。