this指针其作用就是指向成员函数所作用 的对象
例如 Class student{
public:
student setname(){return *this;}
};
int main(){
student a;
a.setname();
}
在上面这个例子中,this变量返回的就是对象a,但是这是一个拷贝的临时对象a,如果对其进行赋值或者初始化等操作对对象a并不会有影响,如果想要返回对象本体,则将上面红色代码改为student &setname(){return *this;}
非静态成员函数中可以直接使用this来代表指向该函数 作用的对象的指针
class Complex {
public:
double real, imag;
void Print() { cout << real << "," << imag ; }
Complex(double r,double i):real(r),imag(i)
{
}
Complex AddOne()
{
this->real ++; //等价于 real ++;
//等价于 Print
this->Print();
return * this;
}
};
int main() {
Complex c1(1,1),c2(0,0);
c2 = c1.AddOne();
}
return 0;
};
} //输出 2,1