First, let's give you a simple example of a class.
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 following is the program that invokes this class
int main ()
{simple
csimple (1);
Csimple.setid (2);
Std::cout << Csimple.getid () << Std::endl;
}
First we look at line 4th: Csimple.setid (2), although this function looks like there are only 1 parameters, actually it has two parameters. C + + will automatically convert this function to SetID (&csimple,2);
Since C + + transforms a function call, the function itself needs to be converted.
void SetID (int nID) {M_nid = NID;}
Convert into:
void SetID (simple* const this, int nID) {This->m_nid = NID;}
C + + Adds a new parameter to the function. The newly added parameter is a pointer to the owning class of this function, named "This". All class member functions have a hidden pointer to a class.
Note that the M_nid has been converted into This->m_nid.
Although most of the time, you don't have to use the "this" pointer explicitly. But sometimes this is also very useful.
1 If your constructor or class member function has a parameter and a member variable with the same name, you can use this to avoid ambiguity
Class something
{
private:
int ndata;
Public:
Something (int ndata)
{
this->ndata = ndata;
}
;
2 Sometimes the function returns "*this" can be very useful. "*this" is reference to the object. This feature allows us to string functions together so that the output of one function can be used as input to another function.
Consider the following class
Class Calc
{
private:
int m_nvalue;
Public:
Calc () {m_nvalue = 0;}
void Add (int nvalue) {m_nvalue + = Nvalue;}
void Sub (int nvalue) {m_nvalue-= nvalue;}
void mult (int nvalue) {m_nvalue *= nvalue;}
int GetValue () {return m_nvalue;}
};
If you want to calculate plus 5, minus 3, and multiplying by 4, like this
Calc CCalc;
Ccalc.add (5);
Ccalc.sub (3);
Ccalc.mult (4);
However, if each function returns "*this", these functions can be strung together.
Class Calc
{
private:
int m_nvalue;
Public:
Calc () {m_nvalue = 0;}
calc& Add (int nvalue) {m_nvalue + = Nvalue; return *this;}
calc& Sub (int nvalue) {m_nvalue-= Nvalue; return *this;}
calc& mult (int nvalue) {m_nvalue *= nvalue; return *this;}
int GetValue () {return m_nvalue;}
};
In this way, the corresponding calculation can be written as
Calc CCalc;
Ccalc.add (5). Sub (3). Mult (4);