W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
類構(gòu)造函數(shù)是該類的特殊成員函數(shù),只要我們創(chuàng)建該類的新對象 ,該函數(shù)便會執(zhí)行。
構(gòu)造函數(shù)的名稱與類完全相同,沒有任何返回類型,構(gòu)造函數(shù)對于為某些成員變量設置初始值非常有用。
以下示例解釋了構(gòu)造函數(shù)的概念-
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());
}
編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-
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());
}
編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-
Object is being created, length=10
Length of line : 10
Length of line : 6
析構(gòu)函數(shù)的名稱與以波浪號(~)為前綴的類的名稱完全相同,它既不能返回值,也不能采用任何參數(shù),如關(guān)閉文件,釋放內(nèi)存等。
以下示例解釋了析構(gòu)函數(shù)的概念-
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());
}
編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-
Object is being created
Length of line : 6
Object is being deleted
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: