W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
指向D語言類指針的方式與指向結(jié)構(gòu)指針以及訪問類指針的成員的方式完全相同,您可以使用成員訪問運算符->運算符,就如同對結(jié)構(gòu)的指針一樣。同樣,與所有指針一樣,您必須在使用指針之前對其進行初始化。
讓我們嘗試以下示例,以了解指向類的指針的概念-
import std.stdio;
class Box {
public:
//Constructor definition
this(double l=2.0, double b=2.0, double h=2.0) {
writeln("Constructor called.");
length=l;
breadth=b;
height=h;
}
double Volume() {
return length * breadth * height;
}
private:
double length; //Length of a box
double breadth; //Breadth of a box
double height; //Height of a box
}
void main() {
Box Box1=new Box(3.3, 1.2, 1.5); //Declare box1
Box Box2=new Box(8.5, 6.0, 2.0); //Declare box2
Box *ptrBox; //Declare pointer to a class.
//Save the address of first object
ptrBox=&Box1;
//Now try to access a member using member access operator
writeln("Volume of Box1: ",ptrBox.Volume());
//Save the address of first object
ptrBox=&Box2;
//Now try to access a member using member access operator
writeln("Volume of Box2: ", ptrBox.Volume());
}
編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-
Constructor called.
Constructor called.
Volume of Box1: 5.94
Volume of Box2: 102
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: