1. 程式人生 > >【C++】類函式呼叫this

【C++】類函式呼叫this

再一次面試中,被問到,函式呼叫時是怎麼知道物件的成員資訊的,用vs除錯了一把:

#include "stdafx.h"
#include <string>
#include <iostream>

class A{
public:
	void test(){
		std::cout << "test : " << num2 << std::endl;
	}
private:
	int num = 3;
	int num2 = 5;
};

int main(int argc, char* argv[])
{
	A a;
	a.test();

	return 0;
}


結論:ecx 攜帶 this指標進棧,通過ecx (dword ptr [this])+ 偏移量獲取成員變數