簡體   English   中英

*this vs this in C++

[英]*this vs this in C++

我明白this是做什么的,但是*thisthis之間有什么區別?

是的,我在我的教科書中用谷歌搜索並閱讀了*this ,但我就是不明白......

this是一個指針,而*this是一個解除引用的指針。

如果你有一個返回this的函數,它將是一個指向當前對象的指針,而一個返回*this的函數將是當前對象的“克隆”,分配在堆棧上——除非你指定了返回類型返回引用的方法。

一個簡單的程序,顯示了操作副本和引用之間的區別:

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

輸出:

1
1
2
3

您可以看到,當我們對本地對象的副本進行操作時,更改不會持久化(因為它完全是一個不同的對象),但對引用或指針的操作確實會持久化更改。

this是一個指向類實例的指針。 *this是對相同的引用 它們的不同之處在於int* i_ptrint& i_ref不同。

沒有真正的區別, this->foo()(*this).foo()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM