D 编程 - 类访问修饰符


数据隐藏是面向对象编程的重要特征之一,它允许防止程序的函数直接访问类类型的内部表示。对类成员的访问限制由类主体中标记为publicprivateprotected 的部分指定。关键字 public、private 和 protected 称为访问说明符。

一个类可以有多个公共、受保护或私有标记的部分。每个部分都保持有效,直到看到另一个部分标签或类主体的右大括号为止。成员和类的默认访问权限是私有的。

class Base { 
  
   public: 
  
  // public members go here 
  
   protected: 
  
  // protected members go here 
  
   private: 
  
  // private members go here 
  
};

D 中的公众成员

公共成员可以从类之外但程序内的任何地方访问。您可以设置和获取公共变量的值,而无需任何成员函数,如下例所示 -

例子

import std.stdio;

class Line { 
   public:
      double length; 

      double getLength() { 
         return length ; 
      }
      
      void setLength( double len ) { 
         length = len; 
      } 
} 
 
void main( ) { 
   Line line = new Line();
   
   // set line length 
   line.setLength(6.0); 
   writeln("Length of line : ", line.getLength());  
   
   // set line length without member function 
   line.length = 10.0; // OK: because length is public 
   writeln("Length of line : ", line.length); 
} 

当上面的代码被编译并执行时,它会产生以下结果 -

Length of line : 6 
Length of line : 10 

私人会员

私有成员变量或函数无法被访问,甚至无法从类外部查看只有类和友元函数可以访问私有成员。

默认情况下,类的所有成员都是私有的。例如,在下面的类中,宽度是一个私有成员,这意味着在您明确标记成员之前,它被假定为私有成员 -

class Box { 
   double width; 
   public: 
      double length; 
      void setWidth( double wid ); 
      double getWidth( void ); 
}

实际上,您需要在私有部分中定义数据并在公共部分中定义相关函数,以便可以从类外部调用它们,如以下程序所示。

import std.stdio;

class Box { 
   public: 
      double length; 

      // Member functions definitions
      double getWidth() { 
         return width ; 
      } 
      void setWidth( double wid ) { 
         width = wid; 
      }

   private: 
      double width; 
}
  
// Main function for the program 
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

受保护会员

受保护的成员变量或函数与私有成员非常相似,但它提供了一个额外的好处,即可以在称为派生类的子类中访问它们。

您将在下一章中学习派生类和继承。现在,您可以检查以下示例,其中一个子类SmallBox派生自父类Box

下面的示例与上面的示例类似,这里的width成员可以由其派生类 SmallBox 的任何成员函数访问。

import std.stdio;

class Box { 
   protected: 
      double width; 
} 
 
class SmallBox:Box  { // SmallBox is the derived class. 
   public: 
      double getSmallWidth() { 
         return width ; 
      }
	  
      void setSmallWidth( double wid ) {
         width = wid; 
      } 
} 
 
void main( ) { 
   SmallBox box = new SmallBox();  
   
   // set box width using member function 
   box.setSmallWidth(5.0); 
   writeln("Width of box : ", box.getSmallWidth()); 
}

当上面的代码被编译并执行时,它会产生以下结果 -

Width of box : 5
d_programming_classes_objects.htm