D 编程 - 类访问修饰符



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

一个类可以有多个 public、protected 或 private 标记的部分。每个部分都保持有效,直到遇到另一个部分标签或类体内的右花括号。成员和类的默认访问权限为 private。

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

D 中的公共成员

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

示例

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 

私有成员

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

默认情况下,类的所有成员都是私有的。例如,在以下类中,width是一个私有成员,这意味着在您显式标记成员之前,它被假定为私有成员:

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

实际上,您需要在 private 部分定义数据,在 public 部分定义相关函数,以便可以从类外部调用它们,如下面的程序所示。

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

受保护的成员

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

您将在下一章学习派生类和继承。现在,您可以查看以下示例,其中一个子类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
广告

© . All rights reserved.