【问题标题】:this and *this differencethis 和 *this 的区别
【发布时间】:2015-10-19 11:39:43
【问题描述】:

下面的程序输出是正确的,但是当我使用这个时出现错误 代替*this。谁能告诉我this和*this是什么意思

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

谁能告诉我this和*this有什么区别?

【问题讨论】:

标签: c++ reference static this


【解决方案1】:

谁能告诉我this和*this是什么意思

this 是指向当前对象的指针。

*this 是当前对象。

您大概知道解引用运算符的作用吗?我不知道你为什么要随意将this 换成*this。不要那样做。

【讨论】:

    猜你喜欢
    • 2011-04-07
    • 1970-01-01
    • 2010-11-06
    • 2011-04-12
    • 2013-10-23
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    相关资源
    最近更新 更多