一个类中的不同对象在调用自己的成员函数时,如何知道要访问哪个对象的数据成员呢?

这个时候就需要通过this指针。每个对象都拥有一个this指针,this指针记录对象的内存地址。简单的来说就是指向当前类实例对象。

(1)this函数只能在成员函数中使用。实际上,成员函数默认第一个参数为T* const this。

  (2)   this在成员函数的开始前构造,在成员函数的结束后清除。

#include <iostream>
#include <string>
using namespace std;
class Dog
{
public:
string name;
void func();
return 0;
};
void Dog::func()
{
this->name = "旺财";
cout << "名字叫:" << this->name << endl;
}

在输出名字之间将对应的名字赋值进去。