33,311
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
using namespace std;
class A{
public:
A () {
this->x =30;
cout<<"x ="<<x <<endl;
cout<<"this->x = "<<x<<endl;
cout<<"this ="<<this<<endl;
}
void print()
{
this->x=10;
cout<<"x ="<<x<<endl;
cout<<"this->x "<< this->x<<endl;
x=100;
cout<<"x ="<<x<<endl;
cout<<"this->x "<< this->x<<endl;
cout<<"this ="<<this<<endl;
}
private:
int x;
};
int main(){
A a; // 调用 A::A(); this == &a
cout<< "address of a ="<<&a<<endl;
a.print(); //调用 A::print; this == &a;
A *p =&a;
cout<< "ptr vlaue: p ="<< p <<endl;
p->print();
A &r =a;
cout<< "address of ref type: r = "<< &r <<endl;
p->print();
return 0;
}
PS :
类的每个非静态函数,都有一个隐藏参数 this;
this 指针,表示 对象,指针语法,调用非静态成员函数的,那个对象的地址。
引用,和对象调用成员函数
1)obj.fun(....);
2)ref.fun(...);
这可以称作对象语法。
指针 调用非静态成员函数
3)ptr->fun(...);
其实就是
4)(*ptr).fun(...);
这可以称作指针语法,可以看作对象语法的一种扩展。
这几种方法调用非静态成员函数
编译器会安排,传入一个隐藏的 this 指针参数。
具体落实到平台 和编译器
X86 Win32 VC
就是把对象的地址,通过 ecx 寄存器,传递给函数。
1) this = &obj; // 对象自己的地址。
2) this = &ref; // 引用的地址,就是被引用对象的地址;
// 引用是对象的别名,可以看作对象自己。
3) this = ptr; // 指针的值,就是所指向的对象的地址。
4) this = ptr; // 指针的值,就是所指向的对象的地址。
pthread_t ulThreadId;
if(0 != pthread_create(&ulThreadId,NULL,ThreadSSKkQuery,(void*)this))