C++之*this的成员函数
PS:今天看到*this之其成员函数,感觉稍微有那么一点点绕,还是写一下吧,增强印象。
啥都不说了,先贴代码。。
#include<iostream>
using namespace std;
class MyScreen
{
public:
int i,j;
MyScreen()
{
this->i=5;
this->j=4;
}
MyScreen &move(int i,int j)
{
this->i=i;
this->j=j;
return *this;
}
MyScreen set()
{
this->i*=10;
this->j*=5;
return *this;
}
} ;
int main()
{
MyScreen myscreen;
myscreen.move(4,3).set();
cout<<myscreen.i<<" "<<myscreen.j<<endl;
return 0;
}
若Move函数前没有&地址符,则返回值是一个拷贝,并不是原先的 myscreen 类,而是拷贝的myscreen类,等价于 MyScreen temp=myscreen.move(4,3); temp.set();
如若加上&地址符 则相当于 MyScreen &temp=myscreen.move(4,3);temp.set();
而temp相当于就是myscreen的引用。
PS:this指针指向的是函数在内存中的手地址,而(*this)才是它的对象,这也就是在函数内部必须用this->或者(*this).去访问成员变量或函数。
顺便说一下const重载的问题,比较弱,我也就不详细解释了。
#include<iostream>
using namespace std;
class MyScreen
{
public:
void do_print()
{
cout<<"No const want to be printed"<<endl;
}
void do_print() const
{
cout<<"const want to be printed"<<endl;
}
} ;
int main()
{
MyScreen myscreen;
myscreen.do_print();
const MyScreen temp;
temp.do_print();
return 0;
}
重点有一点就是:this指针将隐式地从指向非常量的指针转换为指向常量的指针。。
浙公网安备 33010602011771号