W3Cschool
恭喜您成為首批注冊(cè)用戶(hù)
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
重載指與其它函數(shù)具有相同的函數(shù)名,但參數(shù)不相同的函數(shù)實(shí)現(xiàn)。
在同一個(gè)作用域中,可以為同一個(gè)函數(shù)名具有多個(gè)定義。函數(shù)的定義必須在參數(shù)列表中的參數(shù)類(lèi)型/數(shù)量上彼此不同。
以下示例使用相同的函數(shù) print()打印不同的數(shù)據(jù)類(lèi)型-
import std.stdio;
import std.string;
class printData {
public:
void print(int i) {
writeln("Printing int: ",i);
}
void print(double f) {
writeln("Printing float: ",f );
}
void print(string s) {
writeln("Printing string: ",s);
}
};
void main() {
printData pd=new printData();
//Call print to print integer
pd.print(5);
//Call print to print float
pd.print(500.263);
//Call print to print character
pd.print("Hello D");
}
編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-
Printing int: 5
Printing float: 500.263
Printing string: Hello D
您可以重新定義或重載D中可用的大多數(shù)內(nèi)置運(yùn)算符。
可以根據(jù)正在重載的運(yùn)算符,使用字符串op緊隨其后的Add,Sub等來(lái)重載運(yùn)算符,我們可以使運(yùn)算符+重載以添加兩個(gè)框,如下所示。
Box opAdd(Box b) {
Box box=new Box();
box.length=this.length + b.length;
box.breadth=this.breadth + b.breadth;
box.height=this.height + b.height;
return box;
}
對(duì)象作為參數(shù)傳遞,其屬性可以使用該對(duì)象訪問(wèn),可以使用 this 運(yùn)算符訪問(wèn)調(diào)用該運(yùn)算符的對(duì)象 ,如下所述-
import std.stdio;
class Box {
public:
double getVolume() {
return length * breadth * height;
}
void setLength( double len ) {
length=len;
}
void setBreadth( double bre ) {
breadth=bre;
}
void setHeight( double hei ) {
height=hei;
}
Box opAdd(Box b) {
Box box=new Box();
box.length=this.length + b.length;
box.breadth=this.breadth + b.breadth;
box.height=this.height + b.height;
return box;
}
private:
double length; //Length of a box
double breadth; //Breadth of a box
double height; //Height of a box
};
//Main function for the program
void main( ) {
Box box1=new Box(); //Declare box1 of type Box
Box box2=new Box(); //Declare box2 of type Box
Box box3=new Box(); //Declare box3 of type Box
double volume=0.0; //Store the volume of a box here
//box 1 specification
box1.setLength(6.0);
box1.setBreadth(7.0);
box1.setHeight(5.0);
//box 2 specification
box2.setLength(12.0);
box2.setBreadth(13.0);
box2.setHeight(10.0);
//volume of box 1
volume=box1.getVolume();
writeln("Volume of Box1 : ", volume);
//volume of box 2
volume=box2.getVolume();
writeln("Volume of Box2 : ", volume);
//Add two object as follows:
box3=box1 + box2;
//volume of box 3
volume=box3.getVolume();
writeln("Volume of Box3 : ", volume);
}
編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: