在同一個類的成員函數中調用另一個成員函數,**直接寫函數名即可**,編譯器隱式添加 `this->`。無需特殊語法。
class Date {
private:
int year, month, day;
// 輔助函數:判斷閏年
bool isLeapYear() const {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
public:
Date(int y, int m, int d) : year(y), month(m), day(d) {}
// 成員函數調用另一個成員函數
void addOneDay() {
// 直接調用 isLeapYear(),等同於 this->isLeapYear()
int daysInMonth = getDaysInMonth();
if (++day > daysInMonth) {
day = 1;
if (++month > 12) {
month = 1;
++year;
}
}
}
int getDaysInMonth() const {
static const int days[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
if (month == 2 && isLeapYear()) return 29; // 內部調用私有函數
return days[month - 1];
}
};
| 場景 | 調用方式 | 說明 |
|---|---|---|
| 非靜態調用非靜態 | `func()` 或 `this->func()` | 隱式 `this` 指針,編譯器自動綁定當前對象 |
| 非靜態調用靜態 | `ClassName::staticFunc()` 或 `staticFunc()` | 靜態函數無 `this`,推薦類名限定調用 |
| 靜態調用非靜態 | ❌ 編譯錯誤 | 靜態函數無 `this` 指針,無法知道調用哪個對象 |
| 構造函數調用成員函數 | ⚠️ 謹慎 | 對象未完全構造,虛函數調用不會多態 (調用當前類版本),成員可能未初始化 |
| 析構函數調用成員函數 | ⚠️ 謹慎 | 對象正在銷毀,虛函數同樣失去多態,成員可能已銷毀 |
| 虛函數內部調用虛函數 | ✅ 正常多態 | 運行時根據對象動態類型分派 (經典模板方法模式) |
class AlgorithmBase {
public:
// 模板方法:定義算法骨架 (final 防止覆蓋)
void execute() final {
initialize(); // 步驟 1
coreProcess(); // 步驟 2 (多態點)
cleanup(); // 步驟 3
}
protected:
virtual void initialize() { std::cout << "Base Init\n"; }
virtual void coreProcess() = 0; // 純虛函數,子類必須實現
virtual void cleanup() { std::cout << "Base Cleanup\n"; }
};
class ConcreteA : public AlgorithmBase {
protected:
void coreProcess() override { std::cout << "ConcreteA Core\n"; }
};
class ConcreteB : public AlgorithmBase {
protected:
void coreProcess() override { std::cout << "ConcreteB Core\n"; }
};
類內成員函數互調**直接寫函數名**,編譯器處理 `this` 綁定。核心注意點:**靜態函數無 `this`、構造/析構中虛函數不多態、const 傳遞規則**。善用 `this->` 顯式調用可提高代碼可讀性 (區分成員與局部變量)。