C++ 的 * this 是什么,怎么用

在C++中,this指针是一个隐式定义的指针,用于指向当前成员函数所属的对象。例如,在Complex类的成员函数中,this指针指向当前的Complex对象。它可以用于在成员函数内部访问和操作对象的成员变量。this在非静态成员函数中使用,不能在静态成员函数中使用,因为它与特定的对象实例关联。在示例代码中,this被用来在operator+和operator*中组合和乘以Complex对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在 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 是一个指针,使用 * 对它进行解引用时,可以得到当前对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值