问题
I was doing some reading on the 'this' pointer, and I think I understand it more than I originally did, but I still need some clarification. So, by my understanding, if you have
class Simple
{
private:
int m_nID;
public:
Simple(int nID)
{
SetID(nID);
}
void SetID(int nID) { m_nID = nID; }
int GetID() { return m_nID; }
};
The SetID(int nID) function actually is semantically converted into:
void SetID(Simple* const this, int nID) { this->m_nID = nID; }
It makes sense that, there is a this
pointer for all member functions of a class, for the most part. But what happens if you have a member function that takes no arguments? Is there a 'this' pointer? If so, does it point to the return type instead of the argument type?
回答1:
But what happens if you have a member function that takes no arguments? Is there a 'this' pointer? If so, does it point to the return type instead of the argument type?
Even your method do not have any argument, it still have one hidden parameter, that is this
pointer.
回答2:
All class methods that aren't static get a this pointer.
This article gives some ideas about when you might want to use the this pointer.
The presence of the this pointer in C++ has to do with the calling convention. It means there are differences on how space on the stack and in cpu registers is reserved for parameters to functions.
Non static methods in C++ normally use the thiscall convention as opposed to other conventions (varying between compilers and architectures).
来源:https://stackoverflow.com/questions/23165475/in-what-scenario-this-pointer-is-passed-to-the-class-methods