- C++ 基礎
- C++ 首頁
- C++ 概述
- C++ 環境設定
- C++ 基本語法
- C++ 註釋
- C++ Hello World
- C++ 省略名稱空間
- C++ 常量/字面量
- C++ 關鍵字
- C++ 識別符號
- C++ 資料型別
- C++ 數值資料型別
- C++ 字元資料型別
- C++ 布林資料型別
- C++ 變數型別
- C++ 變數作用域
- C++ 多個變數
- C++ 基本輸入/輸出
- C++ 修飾符型別
- C++ 儲存類
- C++ 運算子
- C++ 數字
- C++ 列舉
- C++ 引用
- C++ 日期和時間
- C++ 控制語句
- C++ 決策
- C++ if 語句
- C++ if else 語句
- C++ 巢狀 if 語句
- C++ switch 語句
- C++ 巢狀 switch 語句
- C++ 迴圈型別
- C++ while 迴圈
- C++ for 迴圈
- C++ do while 迴圈
- C++ foreach 迴圈
- C++ 巢狀迴圈
- C++ break 語句
- C++ continue 語句
- C++ goto 語句
- C++ 建構函式
- C++ 建構函式和解構函式
- C++ 複製建構函式
C++ this 指標
this 指標
C++ 中的每個物件都可以透過一個稱為this指標的重要指標訪問其自身的地址。this指標是所有成員函式的隱式引數。因此,在成員函式內部,this 可以用來引用呼叫該函式的物件。
友元函式沒有this指標,因為友元不是類的成員。只有成員函式才有this指標。
this 指標示例
讓我們嘗試以下示例來理解 this 指標的概念:
#include <iostream>
using namespace std;
class Box {
public:
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
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
};
int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
if(Box1.compare(Box2)) {
cout << "Box2 is smaller than Box1" <<endl;
} else {
cout << "Box2 is equal to or larger than Box1" <<endl;
}
return 0;
}
當以上程式碼編譯並執行時,會產生以下結果:
Constructor called. Constructor called. Box2 is equal to or larger than Box1
使用 this 指標返回呼叫物件的引用
要實現鏈式函式呼叫,您需要呼叫物件的引用。您可以使用“this”指標返回呼叫物件的引用。
語法
以下是語法:
Test& Test::func ()
{
return *this;
}
示例
以下示例演示瞭如何返回對呼叫物件的引用
#include <iostream>
using namespace std;
class Coordinates {
private:
int latitude;
int longitude;
public:
Coordinates(int lat = 0, int lon = 0) {
this->latitude = lat;
this->longitude = lon;
}
Coordinates& setLatitude(int lat) {
latitude = lat;
return *this;
}
Coordinates& setLongitude(int lon) {
longitude = lon;
return *this;
}
void display() const {
cout << "Latitude = " << latitude << ", Longitude = " << longitude << endl;
}
};
int main() {
Coordinates location(15, 30);
// Chained function calls modifying the same object
location.setLatitude(40).setLongitude(70);
location.display();
return 0;
}
當以上程式碼編譯並執行時,會產生以下結果:
Latitude = 40, Longitude = 70
廣告