📜  D编程-类和对象

📅  最后修改于: 2020-11-04 05:19:27             🧑  作者: Mango


类是D编程的主要功能,它支持面向对象的编程,通常称为用户定义类型。

一个类用于指定对象的形式,它结合了数据表示形式和用于将该数据处理到一个整齐的包中的方法。一个类中的数据和函数称为该类的成员。

D类定义

定义类时,将为数据类型定义一个蓝图。这实际上并没有定义任何数据,但是它定义了类名的含义,即,该类的对象将由什么组成,以及可以对该对象执行什么操作。

类定义以关键字class开头,后跟类名。和班级身体,用大括号括起来。类定义之后必须是分号或声明列表。例如,我们使用关键字定义Box数据类型,如下所示-

class Box { 
   public: 
      double length;   // Length of a box 
      double breadth;  // Breadth of a box 
      double height;   // Height of a box 
}

关键字public决定了紧随其后的类的成员的访问属性。可以从类外部在类对象范围内的任何位置访问公共成员。您还可以将类的成员指定为私有受保护的成员,我们将在小节中讨论。

定义D对象

类提供了对象的设计图,因此基本上是从类创建对象的。您使用与声明基本类型的变量完全相同的声明类型来声明类的对象。以下语句声明Box类的两个对象-

Box Box1;          // Declare Box1 of type Box 
Box Box2;          // Declare Box2 of type Box 

对象Box1和Box2都有自己的数据成员副本。

访问数据成员

可以使用直接成员访问运算符(。)访问类对象的公共数据成员。让我们尝试以下示例以使事情变得清晰起来-

import std.stdio;

class Box { 
   public: 
      double length;   // Length of a box 
      double breadth;  // Breadth of a box 
      double height;   // Height of a box 
}
  
void main() { 
   Box box1 = new Box();    // Declare Box1 of type Box 
   Box box2 = new Box();    // Declare Box2 of type Box 
   double volume = 0.0;     // Store the volume of a box here  
   
   // box 1 specification 
   box1.height = 5.0; 
   box1.length = 6.0; 
   box1.breadth = 7.0; 
   
   // box 2 specification 
   box2.height = 10.0; 
   box2.length = 12.0; 
   box2.breadth = 13.0;
   
   // volume of box 1 
   volume = box1.height * box1.length * box1.breadth; 
   writeln("Volume of Box1 : ",volume);
   
   // volume of box 2 
   volume = box2.height * box2.length * box2.breadth; 
   writeln("Volume of Box2 : ", volume); 
} 

编译并执行上述代码后,将产生以下结果-

Volume of Box1 : 210 
Volume of Box2 : 1560 

重要的是要注意,不能使用直接成员访问运算符(。)直接访问私有成员和受保护成员。不久,您将学习如何访问私有成员和受保护成员。

D中的类和对象

到目前为止,您已经对D类和对象有了非常基本的了解。还有其他与D类和对象有关的有趣概念,我们将在下面列出的各个小节中进行讨论-

Sr.No. Concept & Description
1 Class member functions

A member function of a class is a function that has its definition or its prototype within the class definition like any other variable.

2 Class access modifiers

A class member can be defined as public, private or protected. By default members would be assumed as private.

3 Constructor & destructor

A class constructor is a special function in a class that is called when a new object of the class is created. A destructor is also a special function which is called when created object is deleted.

4 The this pointer in D

Every object has a special pointer this which points to the object itself.

5 Pointer to D classes

A pointer to a class is done exactly the same way a pointer to a structure is. In fact a class is really just a structure with functions in it.

6 Static members of a class

Both data members and function members of a class can be declared as static.