在 C++ 中,每一個對象都能通過 this 指針來訪問自己的地址。this 指針是所有成員函數的隱含參數。因此,在成員函數內部,它可以用來指向調用對象。this指針針對對象。對於非成員函數,靜態函數和友元函數不能使用this指針,因爲他們指針所有對象。this指針只針對某一個對象。
多繼承和多態的this指針調整
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <Windows.h>
using namespace std;
class Base {
public:
int m_base_a;
void fun_Base() {
printf("####### class Base this %p\n", this);
}
};
class A :virtual public Base {
public:
int m_A_a;
void fun_A() {
printf("####### class A this %p\n", this);
}
};
class B :virtual public Base {
public:
int m_B_a;
void fun_B() {
printf("####### class B this %p\n", this);
}
};
class Derived :public A, public B {
public:
int m_D_a;
void fun_Derived() {
printf("####### class Derived this %p\n", this);
}
};
int main() {
Derived *d = new Derived();
d->fun_Derived();
d->fun_A();
d->fun_B();
d->fun_Base();
A *a = d;
B *b = d;
Base *base = d;
printf("######## d %p, a %p, b %p, base %p",d, a, b, base);
system("pause");
return 0;
}
在這裏打印了派生類和基類的this指針,對於多態編譯器會自動調整對象地址,譬如A *a = d; 編譯器會把d對象內存中屬於a對象的首地址賦值給a。運行如下:this指針其實就是對象的首地址,以隱藏參數的形式傳遞給普通成員函數。