In what scenario 'this' pointer is passed to the class methods? [duplicate]

允我心安 提交于 2019-12-23 22:37:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!