2015-10-19 32 views
1

下面的程序輸出是正確的,但我在的地方使用此 總會有這種錯誤* this.Can有人告訴我這是什麼和*這意味着這和*這種差異

#include<iostream> 
using namespace std; 

class Test 
{ 
private: 
    static int count; 
public: 
    Test& fun(); // fun() is non-static now 
}; 

int Test::count = 0; 

Test& Test::fun() 
{ 
    Test::count++; 
    cout<<Test::count<<" "; 
    return *this; 
} 

int main() 
{ 
    Test t; 
    t.fun().fun().fun().fun(); 
    return 0; 
} 

輸出:

1 2 3 4 

當我在的地方*此錯誤的使用這個來了:

In member function 'Test& Test::fun()': 
invalid initialization of non-const reference of type 'Test&' from an rvalue of type 'Test*' 
    return this; 

可有人告訴我W¯¯通過給出一個很好的例子,帽子就是這個和這個*之間的區別嗎?

+3

[什麼是'this'指針?](http://stackoverflow.com/questions/16492736/what-is-the-this-pointer)和[指針是什麼意思? ](http://stackoverflow.com/questions/4955198/what-does-dereferencing-a-pointer-mean) –

回答

7

誰能告訴我這是什麼和*這意味着

this是指向當前對象。

*this是當前對象。

大家知道,推測是,解除引用操作符的作用是什麼?我不知道你爲什麼試圖交換this*this。根本不要那樣做。