天天看点

问题八:C++中this是干嘛用的

参考C++ Primer (3rd)的13.4章节

每个类成员函数都含有一个指向被调用对象的指针,这个指针被称为this。

所以:

         this表示被调用对象的指针;

         *this表示被调用对象本身;

inline void Screen::home()
{
    this->_cursor = 0;
}
           

此处this表示被调用对象的指针。this->_cursor表示被调用对象的成员变量_cursor,此处对该成员变量赋值。

inline vec3& vec3::operator+=(const vec3 &v)
{
    e[0] += v.e[0];
    e[1] += v.e[1];
    e[2] += v.e[2];
                           
    return *this;
}
           

由于函数定义的函数返回是引用类型,即返回的不是值或者指针,而是对象本身。所以,此处需要return *this来返回对象本身,而不是return this(返回的是指针)。

继续阅读