D語言中的每個對象都可以通 this 訪問自己的指針地址, this 指針是所有成員函數(shù)的隱式參數(shù)。
讓我們嘗試以下示例以了解 this 指針的概念-
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;
}
int compare(Box box) {
return this.Volume() > box.Volume();
}
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
if(Box1.compare(Box2)) {
writeln("Box2 is smaller than Box1");
} else {
writeln("Box2 is equal to or larger than Box1");
}
}
編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-
Constructor called.
Constructor called.
Box2 is equal to or larger than Box1
更多建議: