一、This指针
每个对象都维护自己的一份数据,而成员函数定义是所有对象共享的。
以下两段程序是c++编译器对普通成员函数的内部处理
This指针是一个常量,含有当前实施调用的对象的地址
class Test
{
public:
Test (int i)
{
mI = i;
}
int getI()
{
return mI;
}
static void Print()
{
printf("This is class Test.\n");
}
protected:
private:
int mI;
};
Test a(10);
a.getI();
Test::Print();
void Test_initilize(Test* pThis,int i)
{
pThis->mI = i;
}
int Test_getI(Test* pThis)
{
return pThis->mI;
}
void Test_Print()
{
printf("This is class Test.\n");
}
Test a;
Test_initilize(&a,10);
Test_getI(&a);
Test_Print();
问题??
调用成员函数时,如何知道是对那个对象进行数据操作呢
每个成员函数都有一个隐含的参数,指向接收消息的对象 称为This指针
This的作用:
(1) 用来区分与局部变量重名的数据成员
(2)返回当前对象
(3) 返回当前对象的地址
没学This指针的时候需要这样
class
{
public:
int getA(int _a,int _b)
{
a = _a;
b = _b;
}
protected:
private:
int a;
int b;
};
使用This指针是:
class
{
public:
int getA(int a,int b )
{
this->a = a;
this->b = b;
}
protected:
private:
int a;
int b;
};
class X
{
int m;
public:
void setVal(int m)
{
this->m = m;//区分与函数参数重名的数据成员
}
X& add(const X& a)
{
m += a.m;
return *this;//返回当前对象
}
void copy(const X& a)
{
if(this == &a)
{
return;
m = a.m;//拷贝操作
}
}
protected:
private:
};
#include<iostream>
using namespace std;
class Test
{
public:
Test(int a,int b)//实质是Test(Test *this,int a,int b)
{
this->a = a;
this->b = b;
}
void printT()
{
cout<<"a:"<<a<<endl;
cout<<"b:"<<this->b<<endl;
}
//1 const 写在什么位置 没有关系
//2 const 修饰的是谁?
//3 const 修饰的是形参 a 吗?--不是
//4 const 修饰的是属性 this-a this-b?--不是
//实质是:void OpVar(const Test *this int a,int b)
//void OpVar(const Test *const this int a,int b) 更精确的写法
//const 修饰的是this指针,指针指向的内存的空间不能修改
void OpVar(int a,int b) const//一般写在后边
{
a = 100;
this->a = 100;
this->a = 100;
//cout<<"a:"<<a<<endl;
cout<<"b:"<<this->b<<endl;
}
protected:
private:
int a;
int b;
};
int main()
{
Test t1(1,2);
t1.printT();//实质是printT(&t1)
system("pause");
return 0;
}