# 構造函數和析構函數

## 類的構造函數：

import std.stdio; class Line { public: void setLength( double len ) { length = len; } double getLength() { return length; } this() { writeln("Object is being created"); } private: double length; } void main( ) { Line line = new Line(); // set line length line.setLength(6.0); writeln("Length of line : " , line.getLength()); }

Object is being created
Length of line : 6

## 參數化構造函數：

import std.stdio; class Line { public: void setLength( double len ) { length = len; } double getLength() { return length; } this( double len) { writeln("Object is being created, length = " , len ); length = len; } private: double length; } // Main function for the program void main( ) { Line line = new Line(10.0); // get initially set length. writeln("Length of line : ",line.getLength()); // set line length again line.setLength(6.0); writeln("Length of line : ", line.getLength()); }

Object is being created, length = 10
Length of line : 10
Length of line : 6

## 類的析構函數：

import std.stdio; class Line { public: this() { writeln("Object is being created"); } ~this() { writeln("Object is being deleted"); } void setLength( double len ) { length = len; } double getLength() { return length; } private: double length; } // Main function for the program void main( ) { Line line = new Line(); // set line length line.setLength(6.0); writeln("Length of line : ", line.getLength()); }

Object is being created
Length of line : 6
Object is being deleted