首先举个简单的类的例子
class Simple
{
private:
int m_nID;
public:
Simple(int nID)
{
SetID(nID);
}
void SetID(int nID) { m_nID = nID; }
int GetID() { return m_nID; }
};
下面是调用这个类的程序
int main()
{
Simple cSimple(1);
cSimple.SetID(2);
std::cout << cSimple.GetID() << std::endl;
}
首先我们看第4行:cSimple.SetID(2) , 虽然这个函数看起来只有1个参数,实际上它有两个参数。C++会自动把这个函数转换为SetID(&cSimple,2);
既然C++转换了函数的调用,函数本身也需要转换。
void SetID(int nID) { m_nID = nID; }
转换成:
void SetID(Simple* const this, int nID) { this->m_nID = nID; }
C++给函数新添了一个参数。新添的参数是这个函数的拥有类的一个指针,名字为"this"。所有的类成员函数都有这么个隐藏的指针指向类。
注意m_nID已经被转换成了this->m_nID.
虽然大多数时候,你都不用显式的来用"this"指针。但那时有时候this也非常有用。
1) 如果你的constructor或类成员函数有一个参数和成员变量同名,你可以用this来避免歧义
class Something
{
private:
int nData;
public:
Something(int nData)
{
this->nData = nData;
}
};
2) 有时候函数返回“*this”会非常有用。“*this”是reference to the object。这个特性使得我们可以把函数串在一起,这样一个函数的输出可以作为另一个函数的输入。
考虑下面的类
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; }
};
如果想要计算加5,减3,和乘以4,比如写成这样
Calc cCalc;
cCalc.Add(5);
cCalc.Sub(3);
cCalc.Mult(4);
但是,如果每个函数都返回"*this",这些函数就可以串起来了
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; }
};
这样,相应的计算可以写为
Calc cCalc;
cCalc.Add(5).Sub(3).Mult(4);