在下面的代码中,我放“ this->”还是删除它都没有关系。在两种情况下,它给出相同的输出和结果。那么,在C ++中使用“ this”指针有什么意义呢?在必不可少的地方还有其他用法吗?谢谢。
#include<iostream>
using namespace std;
class square{
int l;
int w;
public:
square(int x, int y){
w = x;
l = y;
}
int getArea(){
return w * l;
};
bool AreaSmallerThan(square c){
if(this->getArea() < c.getArea())
return true;
else
return false;
}
};
int main(){
square A(2,3);
square B(1,3);
if(A.AreaSmallerThan(B))
cout<<"A is smaller than B."<<endl;
else
cout<<"A is NOT smaller than B."<<endl;
return 0;
}
TL; DR:有它的用途。如果您选择良好的命名习惯,通常就不需要经常使用它。
在许多情况下,您需要“指向当前对象的指针”,例如:
struct Foo
{
void MakeCallback(eventid_t eventId)
{
scheduleCallback(eventId, callbackProxyFn, this);
}
static void callbackProxyFn(eventid_t eventId, Foo* foo)
{
// call 'callback' on the relevant object instance.
foo->callback(eventId);
}
void callback(eventid_t eventId);
};
如果您选择使用可怕的命名约定,它也可以用于解决当前对象中的名称与其他作用域之间的冲突。
void Foo::bar(int n)
{
this->n = n;
}
您可以通过为静态变量,全局变量和成员加上前缀来避免这种(双关语)场景(通常的做法):
class Player {
int m_score;
public:
Player(int score) : m_score(score) {}
};
Player g_player1;
static Player s_login; // yeah, I know, terrible, just an example tho.
通常的用途是消除复制/比较运算符中的self:
bool Foo::operator==(const Foo& rhs) const
{
if (this == &rhs)
return true;
...
}
您还可以使用它来生成对当前对象的引用:
foo(const Foo&);
void foo(*this);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句