在 C++ 中,*this
指向当前对象的指针,它是一个隐式定义的指针,指向当前作用域中的对象。this
指针的类型是指向当前对象的类类型指针(Class-type pointer)。
举个例子,下面的代码中,this
指针指向当前的 Complex
类对象:
class Complex {
public:
Complex(double r = 0.0, double i = 0.0): re(r), im(i) {}
Complex operator+(const Complex& rhs) const {
return Complex(re + rhs.re, im + rhs.im);
}
Complex operator*(const Complex& rhs) const {
return Complex(re * rhs.re - im * rhs.im, re * rhs.im + im * rhs.re);
}
double real() const { return re; }
double imag() const { return im; }
private:
double re, im;
};
Complex operator-(const Complex& lhs, const Complex& rhs) {
return Complex(lhs.real() - rhs.real(), lhs.imag() - rhs.imag());
}
int main() {
Complex c1(1, 2), c2(3, 4);
Complex c3 = c1 + c2;
Complex c4 = c1 * c2;
Complex c5 = c1 - c2;
std::cout << "c3 = " << c3.real() << " + " << c3.imag() << "i\n";
std::cout << "c4 = " << c4.real() << " + " << c4.imag() << "i\n";
std::cout << "c5 = " << c5.real() << " + " << c5.imag() << "i\n";
return 0;
}
Complex
类中的成员函数 operator+
和 operator*
分别返回一个 Complex
类型的对象,并利用了*this
的值。当调用 c1 + c2
时,实际上会调用 c1.operator+(c2)
函数,此时,this
指针指向 c1
。
需要注意的是,this
指针只能在非静态成员函数中使用,因为静态成员函数不属于任何一个特定的类对象。此外,* this
是一个指针,使用 *
对它进行解引用时,可以得到当前对象。