May 15, 2013 at 7:07pm UTC
When something like the below is done, what does it mean?
1 2
const sf::Texture& texture=font.getTexture();
//font is type sf::Font, and sf::Font::getTexture() returns const sf::Texture&
Talking about the usage of the & operator in "sf::Texture&"
Aceix.
Last edited on May 15, 2013 at 7:09pm UTC
May 15, 2013 at 7:13pm UTC
Oh, I am sorry.
It means that a const reference is created that will reference the object returned by the function.:)
Consider the example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#include <iostream>
int main()
{
struct A
{
private :
int x;
public :
A( int i = 0 ) : x( i ) {}
A & operator ++()
{
++x;
return ( *this );
}
const int & getX() const { return ( x ); }
} a = 10;
const int &x = a.getX();
std::cout << "x = " << x << std::endl;
++a;
std::cout << "x = " << x << std::endl;
++a;
std::cout << "x = " << x << std::endl;
// Do not do this.:)
int &x2 = const_cast <int &>( a.getX() );
++x2;
std::cout << "x = " << x << std::endl;
}
Last edited on May 15, 2013 at 7:28pm UTC
May 15, 2013 at 8:14pm UTC
If the function returns a const reference then you shoud also use a const reference. Otherwise you may declare a non-const reference.
For example std::vector's operator [] is overloaded to return either a const reference or non-const reference.
Last edited on May 15, 2013 at 8:15pm UTC
May 15, 2013 at 9:16pm UTC
Thank you very much for the information.
Aceix.
May 15, 2013 at 9:51pm UTC
Talking about the usage of the & operator in "sf::Texture&"
In this context, & is not an operator. It's a declarator -- the "reference declarator".
cf.
1 2 3
int value = 3;
int * ptest = &value;
Here & is an operator : the address-of operator
Same deal for the indirection operator and pointer declarator, which are both *.
Andy
Last edited on May 15, 2013 at 10:19pm UTC