1.this 指针的用处:
标识符this指向用户调用成员函数所用对象的指针,换句话说,在访问成员时,默认指向当前对象的指针就是this,而且可以省略,除非是需要引用整个对象市,我们才必须显式使用this。
一个经典的类比是当你进入一个房子时,房子里的一切实际上全称是这个房子的椅子,这个房子的桌子……在默认情况下,省去前面的this并不会造成误解。
2.this 指针的例子:
一个常见的应用是在运算符重载的过程中
class Complex { public: Complex() {}; Complex(double r, double i) :real(r), imag(i) {} Complex(const Complex& comp) :real(comp.real), imag(comp.imag) {} Complex& operator+(const Complex& num) { return Complex(this->real + num.real, this->imag + num.imag); } Complex& operator-(const Complex& num) { return Complex(this->real - num.real, this->imag - num.imag); } Complex& operator*(const Complex& num) { return Complex(this->real*num.real - this->imag*num.imag, this->imag*num.real + this->real* num.imag); } Complex& operator/(const Complex& num) { double a = num.real*num.real + num.imag*num.imag; if(a!=0){ return Complex((this->real*num.real + this->imag*num.imag)/a,( this->imag*num.real -this->real* num.imag)/a); } else { cout << "the second euqal 0" << endl; } } bool operator==(const Complex& num) { return this->real == num.real&&this->imag == num.imag; } bool operator!=(const Complex& num) { return this->real != num.real||this->imag != num.imag; } Complex copy(const Complex& num) { return Complex(num.real, num.imag); } private: double real; double imag; };