开发者

Return reference from class to this

开发者 https://www.devze.com 2022-12-26 18:28 出处:网络
I have the following member of class foo. foo &开发者_JAVA技巧amp;foo::bar() { return this; } But I am getting compiler errors. What stupid thing am I doing wrong?

I have the following member of class foo.

foo &开发者_JAVA技巧amp;foo::bar()
{
   return this;
}

But I am getting compiler errors. What stupid thing am I doing wrong?

Compiler error (gcc): error: invalid initialization of non-const reference of type 'foo&' from a temporary of type 'foo* const'


this is a pointer. So it should be return *this;


As Naveen points out, you need to return *this.

Just a quick tip though: a way to figure out what somewhat obscure compiler errors mean is to try compiling on a different compiler to see if there is a better message. For example, you can use Comeau online.

In this case it gives:

"ComeauTest.c", line 7: error: initial value of reference to non-const must be an
          lvalue
     return this;
            ^

Not sure it's better in this case - but in some cases the messages are way better.

0

精彩评论

暂无评论...
验证码 换一张
取 消