数据隐藏是面向对象编程的重要函数之一,它可以防止程序的函数直接访问类的内部信息。类成员的访问限制由类主体中标有标签的 public , private 和 protected 修饰符指定,成员和类的默认访问权限为私有。
class Base { public: //public 区 protected: //protected 区 private: //private 区 };
public 可以在class以外但在程序内的任何位置访问,您可以在没有任何成员函数的情况下设置和获取公共变量的值,如以下示例所示:
import std.stdio; class Line { public: double length; double getLength() { return length ; } void setLength( double len ) { length=len; } } void main( ) { Line line=new Line(); //设置行长 line.setLength(6.0); writeln("Length of line : ", line.getLength()); //在没有成员函数的情况下设置行长 line.length=10.0; //OK: 因为长度是公开的 writeln("Length of line : ", line.length); }
编译并执行上述代码后,将产生以下输出-
Length of line : 6 Length of line : 10
private 变量或函数无法访问,甚至无法从类外部进行查看,默认情况下,一个类的所有成员都是私有的。例如,在以下类中, width 是私有成员。
class Box { double width; public: double length; void setWidth( double wid ); double getWidth( void ); }
实际上,您需要在私有部分中定义数据,并在公共部分中定义相关函数,以便可以从类外部调用它们,如以下程序所示。
import std.stdio; class Box { public: double length; //成员函数定义 double getWidth() { return width ; } void setWidth( double wid ) { width=wid; } private: double width; } //程序的主要功能 void main( ) { Box box=new Box(); box.length=10.0; writeln("Length of box : ", box.length); box.setWidth(10.0); writeln("Width of box : ", box.getWidth()); }
编译并执行上述代码后,将产生以下输出-
Length of box : 10 Width of box : 10
protected 成员变量或函数与私有成员非常相似,但是它提供了另一个好处,即它的子类对其进行访问。
来源:LearnFk无涯教程网
下面的示例与上面的示例相似,并且 width 成员可由其派生类SmallBox的任何成员函数访问。
import std.stdio; class Box { protected: double width; } class SmallBox:Box { //SmallBox 是派生类。 public: double getSmallWidth() { return width ; } void setSmallWidth( double wid ) { width=wid; } } void main( ) { SmallBox box=new SmallBox(); //使用成员函数设置框宽度 box.setSmallWidth(5.0); writeln("Width of box : ", box.getSmallWidth()); }
编译并执行上述代码后,将产生以下输出-
Width of box : 5
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)