this指针
在每一个成员函数中都包含一个常量指针,我们称其为 this 指针。this 是 C++ 的一个关键字,this 指针指向调用本函数的对象,其值为该对象的首地址。通过该指针,我们可以在成员函数的函数体内访问对象。
#include<iostream>
using namespace std;
class book
{
public:
book(){price = 0.0; title = NULL;}
void copy(book &b);
void display();
private:
double price;
char * title;
};
void book::copy(book &b)
{
//我们用 this 指针先判断被拷贝的对象的引用是否是调用该函数的对象自身,如果是的话则推出函数
if(this == &b)
{
cout<<"same object!"<<endl;
return;
}
else
{
price = b.price;
}
}
void book::display()
{
cout<<"display hello this"<<endl;
}
int main()
{
book Alice;
book Harry;
Harry.copy(Alice);
Harry.display();
Harry.copy(Harry);
Harry.display();
return 0;
}

static void setprice(double price)
{
this->price = price;//compile error
}
//error In static member function 'static void book::setprice(double)':
// error: 'this' is unavailable for static member functions
this 指针出现在 static 成员函数中,编译出错。this 指针只能用于非静态成员函数内
本文探讨了C++中this指针的作用,它如何在成员函数内部访问对象,同时指出了静态成员函数中this指针不可用的特性。通过实例和错误代码展示了两者之间的区别。
5336

被折叠的 条评论
为什么被折叠?



