this指针是一种隐含指针,隐含在每个类的成员函数中,是每个成员函数具有的默认参数,也就是每个成员函数都有一个this指针。this指针指向该函数所属类的对象,因此,成员函数访问类中数据成员的格式可写成: ? this->成员变量;
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
class book
{
public:
book(string name, int num)
{
this->name = name;//this指针标识对象的属性
this->num = num;
}
void init(string name, int num)
{
this->name = name;
this->num = num;
}
void print()
{
cout << name << "\t" << num << endl;
}
//一个对象的成员函数,返回自身
book returnObject()
{
return (*this);//返回对象本身
}
book* returnObjectpoint()
{
return this;
}
book& returnData()
{
return (*this);
}
protected:
string name;
int num;
};
int main()
{
book BOOK("三国", 201);
auto p = &book::print;
BOOK.print();
BOOK.returnObject().print();
return 0;
}
?具体详解参考:(1条消息) this指针详解_askunix-CSDN博客
|