_thiscall
我们知道在c中由三种调用约定:_cdecl,_stdcall和_fastcall,其中_stdcall调用约定是windows平台的。
在c++中还有一种约定:_thiscall调用约定,它是一种类成员方法调用约定。当我们说起_thiscall调用约定时,我们就不得不说一下this指针的概念了。
this指针
this指针,就是类成员方法在调用过程中的一个隐藏的参数,当我们实例化一个对象时,如果我们调用类中的类成员方法,我们就会将对象的地址传给this指针,也可以说是this指针指向了一个实例化的对象,在接下来的操作中都是this指针来调动对象中的类成员变量。
举个例子来说,我们写了一个商品类,并在调用点去调用类中的类成员方法,那类成员方法中的this指针就会指向这个调用点的地址:
#include <iostream>
class commodity
{
public:
commodity(std::string name,float price,int num)
:mname(name),mprice(price),mnum(num)
{}
int buy(/*commodity* const this*/int num)
{
mnum = num;
mprice = mnum * mprice;
return mprice;
}
private:
std::string mname;
float mprice;
int mnum;
};
int main()
{
commodity p1("牛奶",3.5,2);
std::cout <<"two milk's price is :"<< p1.buy(2) <<"$"<< std::endl;
return 0;
}
打印结果如下:
需要注意的是:this指针是一个常量,this指针是一定要初始化的,而且它必须接受对象的地址