C++的this与*this

本文详细探讨了C++中return this与return *this在函数返回时的不同之处。return this返回的是指向当前对象的指针,而return *this返回的是当前对象的一个副本(通常是通过隐式复制构造函数创建的)。通过示例代码,展示了这两种返回方式在对象拷贝、引用及指针接收时的行为差异,帮助理解其在实际编程中的应用。

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

1 摘要

this is a pointer, and *this is a dereferenced pointer.
If you had a function that returned this, it would be a pointer to the current object, while a function that returned *this would be a “clone” of the current object, allocated on the stack – unless you have specified the return type of the method to return a reference.

  • 翻译:this返回的是指针,this返回的是去引用化的指针。return this,即返回当前指向的对象(类型为T* 或者T&);return *this,即返回当前对象的克隆(类型为T),除非你强调返回的是一个引用。

2 详细部分

  • return this 返回的是指针,return * this返回的是该指针指向的对象;而返回类型为Foo,此时会创建Foo类型的对象【与 * this 类型相同】,并将 *this 的值赋给新的Foo类型对象;
    Foo get_copy()
    {
       return *this;
    }
    
  • return * this返回的是该指针指向的对象,返回类型是引用,即引用*this指针指向的对象;
    Foo& get_copy_as_reference()
    {
        return *this;
    }
    
    • return this 返回的就是指针,因此用指向Foo类型的指针(Foo*)接收;
    Foo* get_pointer()
    {
        return this;
    }
    
3 完整代码:

class Foo
{
public:
    Foo()
    {
        this->value = 0;
    }

    Foo get_copy()
    {
        return *this;
    }

    Foo& get_copy_as_reference()
    {
        return *this;
    }

    Foo* get_pointer()
    {
        return this;
    }

    void increment()
    {
        this->value++;
    }

    void print_value()
    {
        std::cout << this->value << std::endl;
    }

private:
    int value;
};

int main() {
    Foo foo;
    foo.increment();
    foo.print_value();

    foo.get_copy().increment();
    foo.print_value();

    foo.get_copy_as_reference().increment();
    foo.print_value();

    foo.get_pointer()->increment();
    foo.print_value();

    return 0;
}

1
1
2
3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值