看this视频花了不少时间,课讲到一半就先去看了博客才能理解了这个this指针,看到最后才明白其实就是一个指向对象本身的一个指针,能在运行对象自身的函数对函数数据成员重名的情况有用,下面将具体的说明是怎样的作用
当我们设置了一个重名的函数数据成员
#include <iostream>
using namespace std;
class Array
{
public:
Array(int len)//有参构造函数
{
len=len;
}
~Array()//析构函数
{
}
void setLen(int len)
{
len=len;
}
int getLen()
{
return len;
}
void printInfo()//打印值
{
cout<<"len="<<len<<endl;
}
private:
int len;
};
int main()
{
Array arr1(10);
arr1.printInfo();
system("pause");
return 0;
}
这时的运行结果是
导致错误的原因是系统分不清是参数对对象成员赋值还是成员对象对参数赋值,下面我们引用this指针
#include <iostream>
using namespace std;
class Array
{
public:
Array(int len)//有参构造函数
{
this->len=len;
}
~Array()//析构函数
{
}
void setLen(int len)
{
this->len=len;
}
int getLen()
{
return this->len;
}
void printInfo()
{
cout<<"len="<<this->len<<endl;
}
private:
int len;
};
int main()
{
Array arr1(10);
arr1.printInfo();
system("pause");
return 0;
}
此时的运行结果如下
我们可以看到我们的赋值成功了,这是因为this->len就是给数据成员赋值,从中可以看出this其实是指向数据成员本身的
下面我们在对程序进行进一步的改装
#include <iostream>
using namespace std;
class Array
{
public:
Array(int len)//有参构造函数
{
this->len=len;
}
~Array()//析构函数
{
}
void setLen(int len)
{
this->len=len;
}
int getLen()
{
return this->len;
}
Array& printInfo()
{
cout<<"len="<<this->len<<endl;
return *this;
}
private:
int len;
};
int main()
{
Array arr1(10);
arr1.printInfo().setLen(20);
arr1.printInfo();
system("pause");
return 0;
}
我们把printInfo函数的数据类型改成了Array类型,返回值是*this,这时的arr1.printInfo()相当于arr1的功能,所以引用 arr1.printInfo().setLen(20)能成功的赋值,运行结果如下
当然我们一可以换另一种方式
#include <iostream>
using namespace std;
class Array
{
public:
Array(int len)//有参构造函数
{
this->len=len;
}
~Array()//析构函数
{
}
void setLen(int len)
{
this->len=len;
}
int getLen()
{
return this->len;
}
Array* printInfo()
{
cout<<"len="<<this->len<<endl;
return this;
}
private:
int len;
};
int main()
{
Array arr1(10);
arr1.printInfo()->setLen(20);
arr1.printInfo();
system("pause");
return 0;
}
和上面一段运行结果都是一致的
我们再来看一下this指针的地址和arr1的地址
#include <iostream>
using namespace std;
class Array
{
public:
Array(int len)//有参构造函数
{
this->len=len;
}
~Array()//析构函数
{
}
void setLen(int len)
{
this->len=len;
}
int getLen()
{
return this->len;
}
void printInfo()
{
cout<<this<<endl;
}
private:
int len;
};
int main()
{
Array arr1(10);
arr1.printInfo();
cout<<&arr1<<endl;
system("pause");
return 0;
}
上面一个是this指针的地址,下面一个是arr1的地址,我们可以看到两者的地址一致
从这三个例子中就可以深切的感受到,*this就是指向了实例本身,也就是:this指针是存在与类的成员函数中,指向被调用函数所在的类实例的地址。
我只能从程序来验证this指针,具体的理论知识参考上一篇,但其实只要我们掌握了命名规范,系统能识别是什么对什么赋值,就会在运行自动加上this指针,也就没有写this指针的必要了。