D-programming-constructor-destructor
提供:Dev Guides
Dプログラミング-コンストラクターとデストラクター
クラスコンストラクター
クラス*コンストラクタ*は、そのクラスの新しいオブジェクトを作成するたびに実行されるクラスの特別なメンバー関数です。
コンストラクターはクラスとまったく同じ名前を持ち、戻り値の型もまったくなく、空でもありません。 コンストラクターは、特定のメンバー変数の初期値を設定するのに非常に役立ちます。
次の例では、コンストラクタの概念を説明します-
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