In C++, I've always known the intialization of Foo& f = _f;
to create an alias to the member _f
. So, from that point on I can call f
and it's just like I was calling _f
.
I have tried doing this where I am se开发者_开发知识库tting an alias to the return of a getter function, and it doesn't seem to be working. How come? This is what I'm trying..
Foo &f = c->getFoo(); //where I have a pointer c that points to an object of type Foo.
Without seeing the declaration, I assume that the problem you have is that you can't get a non const reference for a temporary. So
Foo const&f = c->getFoo();
but
Foo f(c->getFoo());
would probably work as well.
doing Foo &f = c->getFoo() is not an alias. It actually stores the returning address of getFoo() in a reference (Gives you the same object as getFoo() is returning).
It depends on the return type of getFoo(). For example, if your getFoo() returns a Foo& it would work. If your getFoo() returns a const Foo&, then you'll have to do Foo const &f = getFoo().
However, in both cases, you have to make sure that the object returned by getFoo is available in the class c scope, not only in the getFoo() scope (Check that it's not a temporary).
精彩评论