*这个在C ++中 [英] *this vs this in C++

查看:112
本文介绍了*这个在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我明白这个有什么区别, *这个

是的,我已在Google文本中使用Google搜索并阅读了 * this

c>是一个指针, * this 是一个取消引用的指针。



如果你有一个函数返回这个,它将是一个指向当前对象的指针,而返回 * this 的函数将是一个clone

您已指定方法的返回类型以返回引用。



一个简单的程序,其显示对副本和引用进行操作之间的区别:

  #include< iostream> 

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->值<< 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

您可以看到,当我们在本地对象的复制上操作时,更改不会持续(因为它是完全不同的对象),而是对引用或指针进行操作 保持更改。


I understand what this does, but what is the difference between *this and this?

Yes, I have Googled and read over *this in my text book, but I just don't get it...

解决方案

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.

A simple program that shows the difference between operating on copies and references:

#include <iostream>

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;
}

Output:

1
1
2
3

You can see that when we operate on a copy of our local object, the changes don't persist (because it's a different object entirely), but operating on a reference or pointer does persist the changes.

这篇关于*这个在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆